// -*- C -*-

/*
 * The Javascript function in this module implement the policies defined
 * in "RLA0065 - JavaScript URL Mangling" - see that document for a
 * complete discussion of the logic here.
 */


/*
 *  to turn on debugging from a calling HTML page, include
 *
 *   var script_js_debug=1;
 *
 * in a <SCRIPT> element.
 *
 */

// this is defined but unassigned - which makes the test agains
// "null" succeed.
var script_js_debug;

var bViewChange=false;
var bPatternChange=false;
var bRegexPatternChange=false;
var bPageChange = false;
var bSortChanged = false;
var bFilterChanged = false;
var bSelectChanged = false;
var bResetPressed = false;

var setMsgVar= true;
/*
 * This function extends the basic JavaScript escape()
 * functionality by also encoding the '+' sign, which
 * will otherwise be mistaken for a space.
 */
function URLencode(str)
{
	ns = escape(str);
	os = "";

	for(i=ns.indexOf("+");-1!=i;i=ns.indexOf("+"))
	{
		os += ns.substr(0,i);
		os += "%2B";
		ns = ns.substr(i+1);
	}

	if((os.length !=0) && (ns.length != 0)) //add the rest of the original value.
		os += ns;

	if(0 == os.length)
	{
		os = ns;
	}

	debug("urlencode: "  + str + " --> " + os );
	return os;
}

function debug(str)
{
	if(null == script_js_debug )
	{
		return;
	}

	// else
	script_js_debug_window = window.open("","debug")
	script_js_debug_window.document.write(str);
	script_js_debug_window.document.write("<br>");
	return ;
}

//Returns an array containing old items (in current URL) check
function getQueryArgs()
{
	if(null == location.search)
	{
		return new Array();
	}
	args = location.search.split("?");
	if(args.length < 2)
	{
		return new Array();
	}
	s = args[1];
	args = s.split("&");
	return args;
}

/*
 *
 * Scans the query-string of the URL of the current page and returns an array
 * holding the values for the elements of the requested name. That is, if the
 * current query string is
 *
 *   ?arg1=val1&arg2=val2U&arg2=val3&arg4=val4
 *
 * then getFromUrl("arg1") would return ["val1"], and getFromUrl("arg2") would
 * return ["arg2","arg3"]
 *
 */
function getFromUrl(param)
{
	n = new Array();
	count = 0;
	args = getQueryArgs();
	for(i=0;i<args.length;i++)
	{
		nv = args[i].split("=");
		if(nv[0] != param)
		{
			continue;
		}
		n[count++] = nv[1];
	}
	return n;
}


//This will return ["sortParams",[sortParams]]. If no arguments passed return empty array.

function SortTableColumn(sortParams)
{
	if((null == sortParams) || ("" == sortParams) || (0 == arguments.length))
	{
		// no arguments actually passed...
		//return empty array
		return new Array("sortParams",new Array(null));
	}
	curvarg = getFromUrl("sortParams");
	newsortPramas = sortParams;
	//If both parameters are same change the order
	if(sortParams==curvarg)
	{
		if(newsortPramas.charAt(newsortPramas.length-1) == "a")
		{
			var s = newsortPramas.substring(0,newsortPramas.length-1);
			s = s + "d";
			newsortPramas = s;
		}
		else
		{
			if(newsortPramas.charAt(newsortPramas.length-1) == "d")
			{
				var s = newsortPramas.substring(0,newsortPramas.length-1);
				s = s + "a";
				newsortPramas = s;
			}
		}
	}
	return new Array("sortParams",new Array(newsortPramas));
}


/*
 * For a valid argument pnum, returns the array
 *
 *  ["page",[pnum]]
 *
 * Else returns
 *
 *  ["page",[1]]
 *
 */

function Page(pnum)
{
	bPageChange = true;
	if((null == pnum) || ("" == pnum))
	{
	pnum = "1";
	}

	// force conversion to string
	newpage = "" + pnum;
	debug("page: " + newpage);

	return new Array("page",new Array(newpage));
}

/*
 *
 * For a valid argument viewname, returns the array:
 *
 *  ["viewName",[viewname]]
 *
 * If the viewname arg is invalid, the ViewName param
 * from the current URL ("curview") is evaluated and, if
 * valid, the returned array is:
 *
 *  ["viewName",[curview]]
 *
 * If the curview is invalid, the returned array is:
 *
 *  ["viewName",["NoViewInCurrentURL"]]
 *
 * IN ADDITION this function sets a global flag (bViewChange)
 * iff the viewname arg is different from the curview (if any).
 *
 * This is to support gotoPage() implementing a precedence among
 * it's arguments.
 *
 */

function View(viewname)
{
	bViewChange = false;

	curvarg = getFromUrl("viewName");
	if((null == curvarg) || (0 == curvarg.length))
	{
		// current URL has no viewName
		debug("Current URL has no viewName");
		curview = "NoViewInCurrentURL";
	}
	else
	{
		curview = curvarg[0];
	}

	if((null == viewname) || ("" == viewname) || (0 == arguments.length))
	{
		// no arguments actually passed...
		debug("View() not passed any arguments");
		newview = curview;
	}
	else
	{
		newview = viewname;
	}

	debug("View(): " + curview + " -> " + viewname);
	if(curview != viewname)
	{
		bViewChange = true;
	}

	return new Array("viewName",new Array(newview));
}

function OldView(viewname)
{
	bViewChange = false;

	y = new Array();
	v = new Array();

	y = getFromUrl("ViewID");

	// If View() without any arguments current ViewID is returned
	if((viewname ==null) || (viewname == ""))
	{
		v[0] = y[0];
		return new Array("ViewID",v);
	}
	else
	{
		bViewChange = true;
		//Generates new ViewID
		if(y.length>0)
		{
			name = y[0];
			npos = name.indexOf("vn-");
			ViewType =name.substring(0,npos+3);
			w= new Array();
			v[0] = ViewType + viewname;
			w[0] = "ViewID";
			w[1] = v;
			return w;
		}
		else
		{

			v[0] = viewname;
			return new Array("ViewID", v);
		}
	}
}

/*
 *
 * Pattern
 *
 * Returns an array
 *
 *  ["pattern",[nv1,nv2,...]]
 *
 * Where nv1, etc., are URL encoded versions of strings of the form
 *
 *  Name1=Value1
 *
 * (The '=' is rendered as %3D)
 *
 * The set R of nv1,... is formed as the set
 *
 *   R = N v (O ^ ~(O ^ N))
 *
 * where
 *
 *    N is the set of name/value pairs from the function arguments
 *    O is the set of name/value pairs from the current URL
 *
 * See RLA0065 for a complete discussion
 *
 * IN ADDITION this function also sets a global variable bPatternChange
 * to indicate whether the passed-in nv pairs are different - in count
 * or content - from those found on the current page. This is to support
 * the gotoPage() function in applying logic to enforce precedence among
 * it's parameters.
 *
 */
/*					
	if(document.reportBody!=null){
		document.reportBody.accName.value=document.setupReccrPaymentForm.accName.value;
		document.reportBody.payee.value=document.setupReccrPaymentForm.payee.value;
		document.reportBody.payeeAccount.value=document.setupReccrPaymentForm.payeeAccount.value;
	}
	if(document.reportBody==null)
		alert(billingAccountsAlert)
	if(document.reportBody!=null)
		document.reportBody.submit();
}

function uploadContacts() {
document.forms[0].action="./displayCorporateContactUploadForm.do";
document.forms[0].submit();
}
*/

function Pattern(varargs)
{
	bPatternChange = false;

	debug("Pattern() called");
	debug("  args: " + arguments);

	Index = 0;
	Incrementer =0;
	a = new Array();
	b = new Array();
	c = new Array();

	// Array p contains the all the encoded name/value pairs corrosponding
	// to patterns in current URL(Old Items).
	p = getFromUrl("pattern");

	// no arguments in varargs -> return an empty array
	if((null==varargs)|| (varargs =="") || (0 == arguments.length))
	{
		if(0 != p.length)
		{
			// this represents a change, so set the flag
			bPatternChange=true;
		}
		return new Array("pattern",new Array(null));
	}

	if(arguments.length != p.length)
	{
		debug("pattern: lengths differ");
		bPatternChange = true;
	}
	else
	{
		// copy arguments[] array because in IE it's not really
		// an Array() - it's just an Object and doesn't have a
		// sort() method.

		vargs = new Array();
		for(z=0;z<arguments.length;z++)
		{
			vargs[z] = arguments[z];
		}

		vargs.sort();
		p.sort();

		debug("pattern: p = " + p + " [" + p.length + "]");
		debug("pattern: v = " + vargs + " [" + vargs.length + "]");

		for(i=0;i<p.length;i++)
		{
			debug("pattern: cmp " + p[i] + " vs " + vargs[i]);
			if(p[i] != vargs[i])
			{
				debug("pattern: args differ: " + p[i] + " != " + vargs[i]);
				bPatternChange = true;
				break;
			}
		}
	}

	if(true == bPatternChange)
	{
		debug("pattern: change!");
	}
	else
	{
		debug("pattern: no change!");
	}

	// Detect and remove duplicates from varargs
	for(i=0;i<arguments.length;i++)
	{
		nv = arguments[i].split("%3D");
		if((nv.length != 2) || (nv[0] == "") || (nv[1] == ""))
		{
			// skip this argument
			continue;
		}

		found = false;

		// see if the same name occurs again later in the
		// list - if so, ignore the current one
		for(j=i+1;j<arguments.length;j++)
		{
			args = arguments[j].split("%3D");
			if(args[0] == nv[0])
			{
				found = true;
				debug("pattern: dup detected for " + args[0]);
				break;
			}
		}
		if(found == false)
		{
			b[Index++] = nv[0];
			b[Index++] = nv[1];
		}
	}

	// Array b now contains a cleaned list of the valid
	// name/value pairs from the varargs list. These are
	// no longer encoded.

	// This takes a particular name value pair from the p array
	// and takes the name part of it and compares it with the
	// name part of all name value pairs in the b array.
	//
	// If the name in interest is not found it is added to a
	// new array together with its value

	for(i=0;i<p.length;i++)
	{
		if((null == p[i]) || ("" == p[i]))
		{
			// invalid entry
			continue;
		}

		nv = p[i].split('%3D');
		if((2 != nv.length) || ("" == nv[0]) || ("" == nv[1]))
		{
			// invalid entry - skip it
			continue;
		}

		exists = false;

		// look at the name parts of the b array for a match
		for(m=0;m<Index;m= m+2)
		{
			if (nv[0] == b[m])
			{
				exists = true;
				debug("pattern: overriding " + nv[0] );
				break;
			}
		}

		// it goes into the "output" array only if it doesn't exist
		// in the b array.
		if(exists == false)
		{
			a[Incrementer++] = nv[0];
			a[Incrementer++] = nv[1];
		}
	}

	// Add in all the elements from b
	for(i=0;i<Index;i++)
	{
		a[Incrementer++] = b[i];
	}

	// Process the content in array a to generate the array which is the
	// return value from pattern function
	//
	// Resulting array will have two elements
	//
	//  - First element is the string "Pattern"
	//  - Second element is an array containing the encoded name/value pairs

	values = new Array();
	j = 0;
	for (i=0; i<Incrementer;i=i+2)
	{
		values[j] = (a[i] + "%3D" + a[i+1]);
		j = j+1;
	}
	if( values != "")
	{
		c[0] = "pattern";
		c[1] = values;
	}
	return c;
}


/*
 *
 * RegexPattern
 *
 * Accepts a (possibly-empty) list of arguments which are
 * name-value pairs:
 *
 *     [name1,value1][,...]
 *
 *
 * Unlike the Pattern() case, the arguments are not already
 * formed into URL-encoded pairs - this has to be done by
 * this function.
 *
 * Returns an array
 *
 *  ["regexpattern",[nv1,nv2,...]]
 *
 * Where nv1, etc., are URL encoded versions of strings of the form
 *
 *  name1=value1
 *
 * (The '=' is rendered as %3D)
 *
 * The set R of nv1,... is formed in the obvious way from the inputs.
 *
 * IN ADDITION this function also sets a global variable bRegexPatternChange
 * to indicate whether the passed-in nv pairs are different - in count
 * or content - from those found on the current page. This is to support
 * the gotoPage() function in applying logic to enforce precedence among
 * it's parameters.
 *
 */

function RegexPattern(arglist)
{
	bRegexPatternChange = false;

	// copy arguments[] array because in IE it's not really
	// an Array() - it's just an Object and doesn't have a
	// sort() method.
	//
	// At the same time, perform the URL encoding...

	varargs = new Array();
	for(z=0;z<arguments.length/2;z++)
	{
		s = arguments[2*z] + "=" + arguments[2*z+1];
		varargs[z] = URLencode(s);
	}

	debug("RegexPattern() called");
	debug("  args: " + varargs);

	Index = 0;
	Incrementer =0;
	a = new Array();
	b = new Array();
	c = new Array();

	// Array p contains the all the encoded name/value pairs corrosponding
	// to patterns in current URL(Old Items).
	p = getFromUrl("regexpattern");

	// no arguments in varargs -> return an empty array
	if((null==arglist)|| (arglist =="") || (0 == varargs.length))
	{
		if(0 != p.length)
		{
			// this represents a change, so set the flag
			bRegexPatternChange=true;
		}
		return new Array("regexpattern",new Array(null));
	}

	if(varargs.length != p.length)
	{
		debug("regexpattern: lengths differ");
		bRegexPatternChange = true;
	}
	else
	{
		varargs.sort();
		p.sort();

		debug("regexpattern: p = " + p + " [" + p.length + "]");
		debug("regexpattern: v = " + varargs + " [" + varargs.length + "]");

		for(i=0;i<p.length;i++)
		{
			debug("regexpattern: cmp " + p[i] + " vs " + varargs[i]);
			if(p[i] != varargs[i])
			{
				debug("regexpattern: args differ: " + p[i] + " != " + varargs[i]);
				bRegexPatternChange = true;
				break;
			}
		}
	}

	if(true == bRegexPatternChange)
	{
		debug("regexpattern: change!");
	}
	else
	{
		debug("regexpattern: no change!");
	}

	// Detect and remove duplicates from varargs
	for(i=0;i<varargs.length;i++)
	{
		nv = varargs[i].split("%3D");
		if((nv.length != 2) || (nv[0] == "") || (nv[1] == ""))
		{
			// skip this argument
			continue;
		}

		found = false;

		// see if the same name occurs again later in the
		// list - if so, ignore the current one
		for(j=i+1;j<varargs.length;j++)
		{
			args = varargs[j].split("%3D");
			if(args[0] == nv[0])
			{
				found = true;
				debug("pattern: dup detected for " + args[0]);
				break;
			}
		}
		if(found == false)
		{
			b[Index++] = nv[0];
			b[Index++] = nv[1];
		}
	}

	// Array b now contains a cleaned list of the valid
	// name/value pairs from the varargs list. These are
	// no longer encoded.

	// This takes a particular name value pair from the p array
	// and takes the name part of it and compares it with the
	// name part of all name value pairs in the b array.
	//
	// If the name in interest is not found it is added to a
	// new array together with its value

	for(i=0;i<p.length;i++)
	{
		if((null == p[i]) || ("" == p[i]))
		{
			// invalid entry
			continue;
		}

		nv = p[i].split('%3D');
		if((2 != nv.length) || ("" == nv[0]) || ("" == nv[1]))
		{
			// invalid entry - skip it
			continue;
		}

		exists = false;

		// look at the name parts of the b array for a match
		for(m=0;m<Index;m= m+2)
		{
			if (nv[0] == b[m])
			{
				exists = true;
				debug("regexpattern: overriding " + nv[0] );
				break;
			}
		}

		// it goes into the "output" array only if it doesn't exist
		// in the b array.
		if(exists == false)
		{
			a[Incrementer++] = nv[0];
			a[Incrementer++] = nv[1];
		}
	}

	// Add in all the elements from b
	for(i=0;i<Index;i++)
	{
		a[Incrementer++] = b[i];
	}

	// Process the content in array a to generate the array which is the
	// return value from pattern function
	//
	// Resulting array will have two elements
	//
	//  - First element is the string "regexpattern"
	//  - Second element is an array containing the encoded name/value pairs

	values = new Array();
	j = 0;
	for (i=0; i<Incrementer;i=i+2)
	{
		values[j] = (a[i] + "%3D" + a[i+1]);
		j = j+1;
	}
	if( values != "")
	{
		c[0] = "regexpattern";
		c[1] = values;
	}
	return c;
}

/*
 *
 * PrepareSortParams
 *
 * PrepareSortParams() returns an array which contains the SortElements which
 * are going to be in the new URL
 *
 * It accepts a variable argument list, it is the same argument list which gotopage() function
 * accepts and the members of which are arrays created in the other "element" functions including
 * SortElement() function
 *
 * Each of these arrays has the same form -
 *
 *  [<name>,[<value>[...]]]
 *
 * This function discard all the arrays except which is return by SortElement function and creates
 * the array which holds SortElements
 *
 * The arrays return by  PrepareSortParams()has the form
 *
 *  [<name>,[<value>[...]]
 * eg. [<SortElement>,[<calltime%5E0123%5Eto>]
 *
 */


 function PrepareSortParams(ParamArrays)
 {
	newsortArr = new Array();
	allsortvals = new Array();
	sortvals = new Array();
	svals = new Array();
	newSortArray = new Array();
	tempSortArr = new Array();
	c =0;
	inc = 0;
	bIncluded =false;
	bTobeAdded = true;
//Since there is no scinario that could be justified as Sort is not changed when clicking a sort link(even
//clicking the same link) bSortChanged is always set to true. This is used to set the page to 1 when clicking
// a soting link
	bSortChanged = true;

 // ParamArrays contains arrays created in the other "element" functions e.g. Page(),
 // SortElement(), Pattern(), etc..
	for(i =0; i<ParamArrays.length; i++)
	{
 //honers only arrays created by SortElement() function
 //Removes Duplicates
 //i.e. if the gotopage call is like gotopage(....,SortElement(spec1%5EUID1%5Eto),SortElement(spec1%5EUID1%5Eto),...)
 //or like (....,SortElement(spec1%5EUID1%5Eto),SortElement(spec2%5EUID1%5Eto),...)then only the first call to SortElement
 //function with in gotopage function will be honered. Note that in all cases same UID is used as a param
 //to SortElement function
		if(ParamArrays[i][0] == "SortElement")
		{
			bSortCalled = true;
			svals = ParamArrays[i][1];
			if(svals[0] != null)
			{
					nv = svals[0].split("%5E");
					//if(sortvals !="")

					for(n=0; n<sortvals.length; n++)
						{
							if( nv[1] == sortvals[n])
							{
							bTobeAdded = false;
							}
						}
					if (bTobeAdded == true)
						{
							for (m =0; m<nv.length;m++)
							{

								sortvals[inc++] = nv[m];
							}
						}
			}
		}

	}

//Gets the SortlElements in current URL
//Keeps the current URL as a globale variable and do changes on it if and only if
//the current URL has a sortelement which has a UID as same as what is returned by the
//SortElement function else add what is returned by the SortElement as a new element
//When ever a user clicks the same link again then relative direction will be changed


CurrentSortArray = getFromUrl("SortElement");

//If all SortElement function calls have returned null and no SortElements in current URL
// then PrepareSortPrams function will return null too.
	if((sortvals.length == 0) && (CurrentSortArray.length == 0) )
	{
		return new Array("SortElement",new Array(null));
	}

// If view has changed then discard all SortElements in current URL and creats an array
// with only the values retuned by SortElement functions
	if (bViewChange)
	{
		if(sortvals.length != 0)
		{
			e=0;
			for(j=0; j<sortvals.length ; j =j+3)
			{
				tempSortArr[e] =sortvals[j] + "%5E" + sortvals[j+1] + "%5E" + sortvals[j+2];
				e++
			}
			newsortArr[0] = "SortElement";
			newsortArr[1] =  tempSortArr;

			return newsortArr;
		}
		else
		{
			return new Array("SortElement",new Array(null));
		}


	}

	// If ResetUrl called (bResetPressed==true) and the
	// URL spec matches exactly (name and UID) the one in the
	// SortElement() argument list, we set the direction to be
	// the opposite of the URL value.  This must be done in order to
	// allow the sort direction to be toggled when ResetUrl is used.

	if ( bResetPressed )
	{
		for (m =0; m<sortvals.length;m=m+3)
		{
			for(j = 0; j<CurrentSortArray.length ; j++)
			{
				urlsortargs = CurrentSortArray[j].split("%5E");

				if (3 != urlsortargs.length)
				{
					continue;
				}

				if ( urlsortargs[0] == sortvals[m] && urlsortargs[1] == sortvals[m+1] )
				{
					// Toggle the to/fro in the new spec based on the old one
					sortvals[m+2] = (urlsortargs[2] == "to") ? "fro" : "to";

					// We don't need to look any more at the URL once we find a match,
					// so break out of the loop going thru the URL.
					break;
				}
			}

			tempSortArr[c++] = sortvals[m] + "%5E" + sortvals[m+1] + "%5E" + sortvals[m+2];
		}

		newsortArr[0] = "SortElement";
		newsortArr[1] =  tempSortArr;

		return newsortArr;
	}

	for (m =0; m<sortvals.length;m=m+3)
		{
		 bIncluded = false;
		 for(j = 0; j<CurrentSortArray.length ; j++)
			{
				sortargs = CurrentSortArray[j].split("%5E");
				if((3 != sortargs.length))
				{
					continue;
				}

				if (sortargs[1] == sortvals[m+1])
				{
					bIncluded = true;
					if (sortargs[0] == sortvals[m])
					{
						if (sortargs[2] == "to")
						{

							CurrentSortArray[j] = (sortvals[m] + "%5E" + sortvals[m+1] + "%5E" + "fro");
						}
						else
						{

							CurrentSortArray[j] = (sortvals[m] + "%5E" + sortvals[m+1] + "%5E" + "to");
						}
					}
					else
					{


						CurrentSortArray[j] = (sortvals[m] + "%5E" + sortvals[m+1] + "%5E" + sortvals[m+2]);
					}
				}
				else
				{
						continue;

				}


			}//End For

			if (bIncluded == false)
				{

						newSortArray[c++] = sortvals[m] + "%5E" + sortvals[m+1] + "%5E" + sortvals[m+2];

				}



		}

		for(j = 0; j<CurrentSortArray.length ; j++)
		{
			tempSortArr[j] =CurrentSortArray[j];
		}

		for(i = j; i<(j+newSortArray.length) ; i++)
		{
			tempSortArr[i] =newSortArray[i-j];
		}


					newsortArr[0] = "SortElement";
					newsortArr[1] =  tempSortArr;

			return newsortArr;


 }



/*
 *
 * SortElement
 *
 * SortElement() accepts three arguments spec name , UniqueID and relative direction
 * It Url encode these three params with %5E  and returns an array as an output which has two
 * elements . The first element is the text "SortElement" and second element is another array
 * which hold the encoded string.
 *
 *  eg. [<SortElement>,[<calltime%5E0123%5Eto>]
 *
 * In case if one of the params it accept is null this will return array with null value
 *
 */



 function SortElement(arglist)
 {

	ElementString ="";
	newsortvals = new Array();
	ElemntRetArr = new Array();
	if(arguments.length != 3 ||arguments[0] =="" || arguments[1]=="" ||arguments[2]=="")
	{
		return new Array("SortElement",new Array(null));
	}
	else
	{
	for(z =0; z<arguments.length;z++)
		{
			if (ElementString.length>0)
				{
					ElementString = ElementString + "^" + arguments[z];
				}
			else
				{
					ElementString = arguments[z];
				}
		}

		ElementString = URLencode(ElementString);
		ElemntRetArr[0] = ElementString;

				if (ElementString != "")
				{
					newsortvals[0] = "SortElement";
					newsortvals[1] =  ElemntRetArr;
				}
	}
				return newsortvals;
 }





 /*
 *
 * PrepareFilterParams
 *
 * PrepareFilterParams() returns an array which contains the Filter elements which
 * are going to be in the new URL
 *
 * It accepts a variable argument list, it is the same argument list which gotopage() function
 * accepts and the members of which are arrays created in the other "element" functions including
 * Filter() function
 *
 * Each of these arrays has the same form -
 *
 *  [<name>,[<value>[...]]]
 *
 * This function discard all the arrays except which is return by Filter function and creates
 * the array which holds Filter elements
 *
 * The arrays return by  PrepareSortParams()has the form
 *
 *  [<name>,[<value>[...]]
 * eg. [<Filter>,[<calltime%5E0123>]
 *
 */


 function PrepareFilterParams(ParamArrays)
 {
	newfilterArr = new Array();
	allfiltervals = new Array();
	filtervals = new Array();
	svals = new Array();
	newFilterArray = new Array();
	tempFilterArr = new Array();
	c =0;
	inc = 0;
	bFIncluded =false;
	bFTobeAdded = true;

//I assume clicking a link with Filter will always mean changing Filter(even clicking the same link)
// bFilterChanged is always set to true. This is used to set the page to 1 when clicking
// a link with filter

	bFilterChanged = true;

 // ParamArrays contains arrays created in the other "element" functions e.g. Page(),
 // SortElement(), Pattern(), etc..
	for(i =0; i<ParamArrays.length; i++)
	{
 //honers only arrays created by Filter() function
 //Removes Duplicates
 //i.e. if the gotopage call is like gotopage(....,Filter(spec1%5EUID1),Filter(spec1%5EUID1),...)
 //or like (....,Filter(spec1%5EUID1),Filter(spec2%5EUID1),...)then only the first call to Filter
 //function with in gotopage function will be honered. Note that in all cases same UID is used as a param
 //to Filter function
		if(ParamArrays[i][0] == "Filter")
		{
			svals = ParamArrays[i][1];
			if(svals[0] != null)
			{
					nv = svals[0].split("%5E");
					if(filtervals !="")

					for(n=0; n<filtervals.length; n++)
						{
							if( nv[1] == filtervals[n])
							{
							bFTobeAdded = false;
							}
						}
					if (bFTobeAdded == true)
						{
							for (m =0; m<nv.length;m++)
							{

								filtervals[inc++] = nv[m];
							}
						}
			}
		}

	}


	//Gets the FilterElements in current URL
	//Keeps the current URL as a globale variable and do changes on it if and only if
	//the current URL has a Filter which has a UID as same as what is returned by the
	//Filter function else add what is returned by the Filter function as a new element


	CurrentFilterArray = getFromUrl("Filter");

//If all Filter function calls have returned null and  there is no Filter items in
//current URL then PrepareSortPrams function will return null too.
	if((filtervals.length == 0) && (CurrentFilterArray.length == 0))
	{
		return new Array("Filter",new Array(null));
	}

// If view has changed then discard all Filter elements in current URL and creats an array
// with only the values retuned by Filter functions
	if (bViewChange || bResetPressed)
	{
		if(filtervals.length != 0)
		{
			e=0;
			for(j=0; j<filtervals.length ; j =j+2)
			{
				tempFilterArr[e] =filtervals[j] + "%5E" + filtervals[j+1];
				e++
			}
			newfilterArr[0] = "Filter";
			newfilterArr[1] =  tempFilterArr;

			return newfilterArr;
		}

	 else
		{
			return new Array("Filter",new Array(null));
		}

	}



	for (m =0; m<filtervals.length;m=m+2)
		{
		 bFIncluded = false;
		 for(j = 0; j<CurrentFilterArray.length ; j++)
			{
				filterarg = CurrentFilterArray[j].split("%5E");
				if((2 != filterarg.length))
				{
					continue;
				}

				if (filterarg[1] == filtervals[m+1])
				{
					bFIncluded = true;
					if (filterarg[0] == filtervals[m])
					{
						continue;
					}
					else
					{


						CurrentFilterArray[j] = (filtervals[m] + "%5E" + filtervals[m+1]);
					}
				}
				else
				{
						continue;

				}


			}//End For

			if (bFIncluded == false)
				{

						newFilterArray[c++] = (filtervals[m] + "%5E" + filtervals[m+1]);

				}



		}

		for(j = 0; j<CurrentFilterArray.length ; j++)
		{
			tempFilterArr[j] =CurrentFilterArray[j];
		}

		for(i = j; i<(j+newFilterArray.length) ; i++)
		{
			tempFilterArr[i] =newFilterArray[i-j];
		}


					newfilterArr[0] = "Filter";
					newfilterArr[1] =  tempFilterArr;

			return newfilterArr;


 }



 /*
 *
 * Filter
 *
 * Filter() accepts two arguments Filter Name, UniqueID
 * It Url encode these two params with %5E  and returns an array as an output which has two
 * elements . The first element is the text "Filter" and second element is another array
 * which hold the encoded string.
 *
 *  eg. [<Filter>,[<calltime%5E0123>]
 *
 * In case if one of the params it accept is null this will return array with null value
 *
 */


 function Filter(arglist)
 {



	ElementString ="";
	newfiltervals = new Array();
	ElemntRetArr = new Array();
	if(arguments.length != 2 ||arguments[0] =="" || arguments[1]=="")
	{
		return new Array("Filter",new Array(null));
	}
	else
	{
	for(z =0; z<arguments.length;z++)
		{
			if (ElementString.length>0)
				{
					ElementString = ElementString + "^" + arguments[z];
				}
			else
				{
					ElementString = arguments[z];
				}
		}

		ElementString = URLencode(ElementString);
		ElemntRetArr[0] = ElementString;

				if (ElementString != "")
				{
					newfiltervals[0] = "Filter";
					newfiltervals[1] =  ElemntRetArr;
				}
	}
				return newfiltervals;

 }




/*
 *
 * PrepareSelectParams
 *
 * PrepareSelectParams() returns an array which contains the Select elements which
 * are going to be in the new URL
 *
 * It accepts a variable argument list, it is the same argument list which gotopage() function
 * accepts and the members of which are arrays created in the other "element" functions including
 * Select() function
 *
 * Each of these arrays has the same form -
 *
 *  [<name>,[<value>[...]]]
 *
 * This function discard all the arrays except which is return by Select function and creates
 * the array which holds Select elements
 *
 * The arrays return by  PrepareSortParams()has the form
 *
 *  [<name>,[<value>[...]]
 * eg. [<Select>,[<status%5E0123%5E20>]
 *
 */


 function PrepareSelectParams(ParamArrays)
 {
	newselectArr = new Array();
	allselectvals = new Array();
	selectvals = new Array();
	svals = new Array();
	newSelectArray = new Array();
	tempselectArr = new Array();
	c =0;
	inc = 0;
	bSIncluded =false;
	bSTobeAdded = true;

//I assume clicking a link with Select will always mean changing Select(even clicking the same link)
// bFilterChanged is always set to true. This is used to set the page to 1 when clicking
// a link with Select

	bSelectChanged = true;

 // ParamArrays contains arrays created in the other "element" functions e.g. Page(),
 // SortElement(), Pattern(), etc..
	for(i =0; i<ParamArrays.length; i++)
	{
 //honers only arrays created by Select() function
 //Removes Duplicates
 //i.e. if the gotopage call is like gotopage(....,Select(spec1%5EUID1),Select(spec1%5EUID1),...)
 //or like (....,Select(spec1%5EUID1),Select(spec2%5EUID1),...)then only the first call to Select
 //function with in gotopage function will be honered. Note that in all cases same UID is used as a param
 //to Select function
		if(ParamArrays[i][0] == "Select")
		{
			svals = ParamArrays[i][1];
			if(svals[0] != null)
			{
					nv = svals[0].split("%5E");
					if(selectvals !="")

					for(n=0; n<selectvals.length; n++)
						{
							if( nv[1] == selectvals[n])
							{
							bSTobeAdded = false;
							}
						}
					if (bSTobeAdded == true)
						{
							for (m =0; m<nv.length;m++)
							{

								selectvals[inc++] = nv[m];
							}
						}
			}
		}

	}


	//Gets the SelectElements in current URL
	//Keeps the current URL as a globale variable and do changes on it if and only if
	//the current URL has a Select which has a UID as same as what is returned by the
	//Select function else add what is returned by the Select function as a new element


	CurrentSelectArray = getFromUrl("Select");

//If all Select function calls have returned null and  there is no Select items in
//current URL then PrepareSelectPrams function will return null too.
	if((selectvals.length == 0) && (CurrentSelectArray.length == 0))
	{
		return new Array("Select",new Array(null));
	}

// If view has changed then discard all Select elements in current URL and creats an array
// with only the values retuned by Select functions
	if (bViewChange || bResetPressed)
	{
		if(selectvals.length != 0)
		{
			e=0;
			for(j=0; j<selectvals.length ; j =j+3)
			{
				tempselectArr[e] =selectvals[j] + "%5E" + selectvals[j+1]+ "%5E" + selectvals[j+2];
				e++
			}
			newselectArr[0] = "Select";
			newselectArr[1] =  tempselectArr;

			return newselectArr;
		}

	 else
		{
			return new Array("Select",new Array(null));
		}

	}



	for (m =0; m<selectvals.length;m=m+3)
		{
		 bSIncluded = false;
		 for(j = 0; j<CurrentSelectArray.length ; j++)
			{
				Selectarg = CurrentSelectArray[j].split("%5E");
				if((3 != Selectarg.length))
				{
					continue;
				}

				if (Selectarg[1] == selectvals[m+1])
				{
					bSIncluded = true;
					if (Selectarg[0] == selectvals[m])
					{
						if((Selectarg[2]=="") && (selectvals[m+2]==""))
						{
							continue;
						}
						else
						{
							CurrentSelectArray[j] = (selectvals[m] + "%5E" + selectvals[m+1]+ "%5E" + selectvals[m+2]);
						}

					}
					else
					{


						CurrentSelectArray[j] = (selectvals[m] + "%5E" + selectvals[m+1]+ "%5E" + selectvals[m+2]);
					}
				}
				else
				{
						continue;

				}


			}//End For

			if (bSIncluded == false)
				{

						newSelectArray[c++] = (selectvals[m] + "%5E" + selectvals[m+1]+ "%5E" + selectvals[m+2]);

				}



		}

		for(j = 0; j<CurrentSelectArray.length ; j++)
		{
			tempselectArr[j] =CurrentSelectArray[j];
		}

		for(i = j; i<(j+newSelectArray.length) ; i++)
		{
			tempselectArr[i] =newSelectArray[i-j];
		}


					newselectArr[0] = "Select";
					newselectArr[1] =  tempselectArr;

			return newselectArr;


 }





/*
 *
 * Select
 *
 * Select() accepts three arguments select Name, UniqueID , count
 * It Url encode these three params with %5E  and returns an array as an output which has two
 * elements . The first element is the text "Select" and second element is another array
 * which hold the encoded string.
 *
 *  eg. [<Select>,[<Status%5E01343%5E10>]
 *
 * In case if one of the params it accept is null this will return array with null value
 *
 */


 function Select(arglist)
 {

	ElementString ="";
	newselectvals = new Array();
	ElemntRetArr = new Array();
	LengthArr = new Array();



	if((arguments.length == 3) || (arguments.length == 2))
	{
		for(i=0;i<arguments.length;i++)
			{
				if(arguments[i] == "")
				{
					return new Array("Select",new Array(null));
				}
				LengthArr[i] = arguments[i];
			}


		if(arguments.length == 2)
		{
			LengthArr[i] ="";
		}
	}
	else
	{
		return new Array("Select",new Array(null));
	}


	for(z =0; z<LengthArr.length;z++)
		{
			if (ElementString.length>0)
				{
					ElementString = ElementString + "^" + LengthArr[z];
				}
			else
				{
					ElementString = LengthArr[z];
				}
		}

		ElementString = URLencode(ElementString);
		ElemntRetArr[0] = ElementString;

				if (ElementString != "")
				{
					newselectvals[0] = "Select";
					newselectvals[1] =  ElemntRetArr;
				}

				return newselectvals;

 }

/*
  *
  *
  * ResetAll()
  *
  * Returns an array containing with two elements, first element is text "Reset" and second element is an array
  * with null value and pattern elements
  *
  * This function also set a global boolean variable(bResetPressed) to true
  *
  *
  */

  function ResetUrl()
  {

	bResetPressed = true;
	return new Array("Reset",new Array(null)) ;

  }




/*
 *
 * gotoPage() calculates a "target" URL based on the URL of the
 * current page and the arguments passed to it.
 *
 * It accepts a variable argument list, the members of which are
 * the arrays created in the other "element" functions e.g. Page(),
 * Sort(), Pattern(), etc..
 *
 * Each of these arrays has the same form -
 *
 *  [<name>,[<value>[...]]]
 *
 * e.g. ["page",["1"]]
 *
 * This is a compact way of encoding  (name,value) pairs that will be
 * put into the "new" URL.
 *
 * gotoPage() constructs a new URL by merging the query-string from the URL
 * of the current page (if any) with the passed values, with the passed
 * values overriding the "current" args. So, if the query-string for the
 * current URL includes:
 *
 *  ...&page=3&...
 *
 * and the array ["page",["4"]] is passed in, the caclculated URL will
 * include ...&page=4&...
 *
 * There are several dependencies between arguments that gotoPage() has
 * to resolve.
 *
 * 1) If the "new" page has a different View or different list of Patterns
 *    or RegexPatterns, any "page" parameter in the current URL will be
 *    discarded. If there is an explicit page value set via the parameters
 *    it will be honored, otherwise there will be NO page value in the URL,
 *    which is the same as "page=1".
 *
 * 2) If the "new" page has a different View, then Patterns, RegexPatterns,
 *    and sortParams from the "current" URL will be discarded.
 *
 * 3) If the "new" page has a different View, Pattern, RegexPattern, or Page,
 *    then the sortParams from the "current" URL will be discarded.
 *
 */

function gotoPage(paramlist)
{
	x = new Array;
	countup = 0;

	debug("gotoPage() called");

	// Finds old items in current URL which are only found in it
	// Array X holds the result items that will form the new URL

	args = getQueryArgs();




	//filterargs contains all the sort elements that is going to be apear in new URL
	  filterargs = PrepareFilterParams(arguments);

	  //sortargs contains all the sort elements that is going to be apear in new URL
	  sortargs = PrepareSortParams(arguments);

	  //selectargs contains all the select elements that is going to be apear in new URL
	  selectargs = PrepareSelectParams(arguments);



	for (i=0;i<args.length;i++)
	{

		nv =args[i].split("=");
		if((null == nv) || (2 != nv.length))
		{
			// invalid querystring arg - skip it
			debug("invalid querystring arg: " + args[i] + " - skipping");
			continue;
		}

		// handle special Page override as needed
		if(("page" == nv[0]) && (bViewChange || bPatternChange || bRegexPatternChange ||
								 bSortChanged || bFilterChanged || bSelectChanged || bResetPressed))
		{
			// suppress use of "current page"
			debug("gotoPage: page 1 override");
			continue;
		}

		// handle Pattern override as needed
		if(("pattern" == nv[0]) && (bViewChange))
		{
			// suppress use of "current pattern"
			debug("gotoPage: discarding current pattern because view has changed");
			continue;
		}

		// handle RegexPattern override as needed
		if(("regexpattern" == nv[0]) && (bViewChange))
		{
			// suppress use of "current regexpattern"
			debug("gotoPage: discarding current regexpattern because view has changed");
			continue;
		}

		// handle Sort override as needed
		if(("sortParams"==nv[0]) && (bViewChange || bPatternChange || bRegexPatternChange ||bPageChange))
		{
			// suppress use of current sort parameters
			debug("gotoPage: discarding current sort parameters because something has changed");
			continue;
		}


		found = false;

		for(j=0;j<arguments.length;j++)
		{
			debug("checking: " + nv[0] + " vs. " + arguments[j][0]);
			if (nv[0] == arguments[j][0])
			{

				found =true;
				break;
			}
		}

		if(found == false)
		{
			if((nv[0] == "SortElement") || (nv[0] == "Filter") || (nv[0] == "Select"))
				{
					break;
				}

			x[countup++] = nv[0];
			x[countup++] = nv[1];
		}
	}



	// Array X now holds the items from the current URL
	// Now Populate the array X with the new items from value arrays

	for (k=0; k<arguments.length;k++)
	{

			debug("gotoPage arg " + k + ": " + arguments[k]);

			nname = arguments[k][0];
			nvals = arguments[k][1];
			if((nname == "SortElement") || (nname == "Filter") || (nname == "Select"))
				{
					continue;
				}
			if(nvals[0] != null)
			{
				for (m =0; m<nvals.length;m++)
				{

					x[countup++] = nname;
					x[countup++] = nvals[m];
				}
			}

	}

	//Add SortElements one by one to the array which is used to create the new url
	if(sortargs[1][0] != null)
	{
		for(z=0;z<sortargs[1].length;z++)
		{
			x[countup++] = "SortElement";
			x[countup++] =	sortargs[1][z];
		}

	}

	//Add Filter elements one by one to the array which is used to create the new url
	if(filterargs[1][0] != null)
	{
		for(z=0;z<filterargs[1].length;z++)
		{
			x[countup++] = "Filter";
			x[countup++] =	filterargs[1][z];
		}

	}


	//Add Select elements one by one to the array which is used to create the new url
	if(selectargs[1][0] != null)
	{
		for(z=0;z<selectargs[1].length;z++)
		{
			x[countup++] = "Select";
			x[countup++] =	selectargs[1][z];
		}

	}


	// reset defaults
	bViewChange = false;
	bPatternChange = false;
	bRegexPatternChange = false;
	bPageChange = false;
	bSortChanged = false;
	bFilterChanged = false;
	bSelectChanged = false;
	bResetPressed =false;

	// Process the array X and generate new URL
	query = "";
	for(i=0;i<x.length/2;i++)
	{
		if(query.length>0)
		{
			query = query + "&";
		}
		query = query + x[2*i] + "=" + x[2*i+1];
	}

	if(query != "")
	{
		url = "displayView.do?" + query ;
	}
	else
	{
		url = "displayView.do";
	}

	debug("new url: " + url);
	return url;
}


// This function add the attribute subIdx=<subIdx> to the url
function gotoSubIdxPage(paramlist, subIdx)
{
	// let the gotoPage does its work
	var url = gotoPage(paramlist);

	// add the subIdx to url
	url = url + "&subIdx=" + subIdx;

	return url;
}

// This function will change the action of a form dynamically and then submit
function doAction(action, formname) {
	var objForm = formname != '' ? document.forms[formname] : document.forms[0];
	objForm.action = action;
	objForm.submit();
	return false;
}

// This function sets the action of the form without submitting
function setAction(action, formname) {
	var objForm = formname != '' ? document.forms[formname] : document.forms[0];
	objForm.action = action;
}

// This function verifies that the entered page number is good -->
function checkPageNumber(fieldname,limit)
{
		var pattern = /^[0-9]*$/;
		var field   = document.getElementById(fieldname);
		if(pattern.test(field.value)==false)
		{
			showError(pageNumberOutOfRange+limit);
			return false;
		}
		else
		{
			if((field.value > limit)||(field.value <= 0))
			{
				showError(pageNumberOutOfRange+limit);
				return false;
			}
		}
}

// this function is call the criteria Action when the user select the hierarchyType, hierarchyName and elementName
// in the hierarchyCriteria
// This method was commented as it is not called inside jsp page and conflict with the same method in hierarchy as well.
/*function gotoCriteriaURL(changeSelect)
{
		document.criteriaForm.changeSelect.value = changeSelect;
		document.criteriaForm.submit();
}*/


//this allows multiple select item moves
function move_item(from, to,obj)
{ 
  var f;
  var SI; /* selected Index */
  if(from.options.length>0)
  {
    for(i=0;i<from.length;i++)
    {
      if(from.options[i].selected)
      {
        SI=from.selectedIndex;
        f=from.options[SI].index;
		if(to.length>0 && to.options[to.length-1].disabled) /* for the empty disabled option added for W3C compliance requirement*/
		{
			to.options[to.length-1]=new Option(from.options[SI].text,from.options[SI].value);
		}
		else
		{
			to.options[to.length]=new Option(from.options[SI].text,from.options[SI].value);
		}
        from.options[f]=null;
        i--; /* make the loop go through them all */
      }
    }
  }
  $(obj).attr("disabled",true);
}

function ableMove(from,ableButton){
	var flag = false ;
	if(from.options.length>0)
  {
    for(i=0;i<from.length;i++)
    {
      if(from.options[i].selected)
      {
        flag = true ;
      }
    }
  }
  
  if(flag){
	$("."+ableButton).removeAttr("disabled");
  }
}

function getDispFields(form)
{
    var str="";
	var submitFlag = true
	var i;
	var dtFrom=document.getElementById("reportPeriodStart");
 	var dtTo=document.getElementById("reportPeriodEnd");
/*
    Not sure why it's validating the fields here and assuming all fields are number.
    Individual fields are already validated at the field itself.
    For CR: 12-1J3HRBD, Duration field needs to be treated differently, otherwise, 
    it will never submit the form if duration is specified since the pattern is not number.
    Comment out to fix the issue.

	for(i=0; i<form.length; i++ )
	{

		if (form.elements[i].value == "Between" )
		{
			setMsgVar = false;
			if(!validateNumberField(form.elements[i+1]))
			{
				submitFlag = false;
				break;
			}
			else if (!validateNumberField(form.elements[i+2]))
			{
				submitFlag = false;
				break;
			}

			else if ((form.elements[i+1].value == "" )||(form.elements[i+2].value == "" ))
			{
				alert(invalidNumber);
				submitFlag = false;
				break;

			}
		}


		if (form.elements[i].value == "GreaterThan" )
		{
			setMsgVar = false;
			if(!validateNumberField(form.elements[i+1]))
			{
				submitFlag = false;
				break;
			}

			else if(form.elements[i+1].value == "" )
			{
				alert(invalidNumber);
				submitFlag = false;
				break;

			}
		}


		if (form.elements[i].value == "LessThan" )
		{
			setMsgVar = false;
			if(!validateNumberField(form.elements[i+1]))
			{
				submitFlag = false;
				break;
			}

			else if(form.elements[i+1].value == "" )
			{
				alert(invalidNumber);
				submitFlag = false;
				break;

			}
		}

		if (form.elements[i].value == "EqualTo" )
		{
			setMsgVar = false;
			if(!validateNumberField(form.elements[i+1]))
			{
				submitFlag = false;
				break;
			}
			else if(form.elements[i+1].value == "" )
			{
				alert(invalidNumber);
				submitFlag = false;
				break;

			}
		}
	}
*/

	if (parseInt(dtFrom.value)>parseInt(dtTo.value)){
		showError(invalidDateRange2);
        return false;
    }else{
    var field= form.disp_fields;
    if(field.length > 0 )
    {
        for(i=0;i<field.length;i++)
        {
           // alert(field.options[i].value);
            if (i==(field.length-1))
            {
               str=str+field.options[i].value;
            }
            else
            {
            str=str+field.options[i].value+"||";
            }
        }
        form.disp_cols.value=str;
    }
    else
    {
    	showError(emptyDispalyField);
    	submitFlag = false;
    }

	if (submitFlag == true)
	{
	    form.submit();
	}
	}
}

// this function validates the date fields of billing reports
// Harendra Corray - 01/19/2004


var dtCh= "/";
var minYear=1900;
var maxYear=2100;
var dtFlag=""

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   }
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		showError(invalidDateRange)
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		if(dtFlag == "from")
		showError(invalidFromDate)
		else if (dtFlag == "to")
		showError(invalidToDate)
		dtFlag=""
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){

		if(dtFlag == "from")
		showError(invalidFromDate)
		else if (dtFlag == "to")
		showError(invalidToDate)
		dtFlag=""
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){

		if(dtFlag == "from")
		showError(invalidYearDigits+minYear+invalidYearDigitsAnd+maxYear+invalidFromYearDigits)
		else if (dtFlag == "to")
		showError(invalidYearDigits+minYear+invalidYearDigitsAnd+maxYear+invalidToYearDigits)
		dtFlag=""
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		showError(invalidDateRange)
		return false
	}
return true
}

function validatePromptsDateFieldsOnInput()
{
	var dtFrom=document.forms['findCallForm'].fromDate;
	var dtTo=document.forms['findCallForm'].toDate;
	if(dtFrom.value.length == 0 && dtTo.value.length == 0) {
		return true
	}
	if (dtFrom.value.length > 0 && isDate(dtFrom.value,dtFlag="from")==false){
		dtFrom.focus()
		return false
	}
	else if (dtTo.value.length > 0 && isDate(dtTo.value,dtFlag="to")==false){
		dtTo.focus()
		return false
	}

    if (dtFrom.value.length > 0 && dtTo.value.length > 0 && Date.parse(dtFrom.value) > Date.parse(dtTo.value)) {
    	showError(invalidDateRange2)
    	return false;
    }
    else{
    	return true;
    }

}

function validateDateFields()
{
	if(document.forms['findCallForm'].radioPeriodRange[1].checked){
		return validatePromptsDateFieldsOnSelect();
	}
	else if (document.forms['findCallForm'].radioPeriodRange[2].checked){
		return true;// validatePromptsDateFieldsOnInput();
	}
	else{
		return true;
	}
 }

function validatePromptsDateFields()
{
	var dtFromValue=$('#reportForm').find('[name=reportPeriodStart]').val(); 
    var dtToValue=$('#reportForm').find('[name=reportPeriodEnd]').val(); 
	
    if (parseInt(dtFromValue) > parseInt(dtToValue)) {
        showError(invalidDateRange2)
        return false;
    }
	else return true;

 }

function validateCustomDateFields()
{


	var dtFrom=document.customReportForm.dateRange1
	var dtTo=document.customReportForm.dateRange2

	if(dtFrom.value.length == 0 && dtTo.value.length == 0) {
		return true
	}

	if (dtFrom.value.length > 0 && isDate(dtFrom.value,dtFlag="from")==false){
		dtFrom.focus()
		return false
	}
	else if (dtTo.value.length > 0 && isDate(dtTo.value,dtFlag="to")==false){
		dtTo.focus()
		return false
	}

    if (dtFrom.value.length > 0 && dtTo.value.length > 0 && Date.parse(dtFrom.value) > Date.parse(dtTo.value)) {
        showError(invalidDateRange2)
        return false;
    }
	else return true

 }

function validateReportNameField(string)
{
        var illegalChars = /[\(\)\<\>\,\;\:\\\/\[\]\"\#\%\*\|\?\&]/;
        removeError();
        if(string.length == 0)
        {
            showError(invalidReportName);
            return false;

        }

		if(string.charAt(0) == ' ')
        {
            showError(invalidReportNameLeadingSpace);
            return false;

        }

        if(illegalChars.test(string))
        {
            showError(reportNameIllegalCharacter);
            return false;
        }
	    else{

            return true;
        }

}

function validateDateRange(tempDateRange1,tempDateRange2)
{


	var dtFrom= tempDateRange1;
	var dtTo=tempDateRange2;


	if(dtFrom.length == 0 && dtTo.length == 0) {
		return true;
	}

	if (dtFrom.length > 0 && isDate(dtFrom)==false){
		dtFlag="from"

		//dtFrom.focus()
		return false;
	}
	else if (dtTo.length > 0 && isDate(dtTo)==false){
		dtFlag="to"
		//dtTo.focus()
		return false;
	}

    if (dtFrom.length > 0 && dtTo.length > 0 && Date.parse(dtFrom) > Date.parse(dtTo)) {
        showError(invalidDateRange2)
        return false;
    }
	else {  return true;}

 }





function vlidateNumericField_CustomizeAcc(total1){
 	var strValidChars = "0123456789.";
   var strChar;
   var blnResult = true;

   if (total.length == 0) { showError(numericValueNeeded); return false; }

   else{
   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }

      }

	  if (blnResult == true){

     getDispFields(document.customReportForm);

	  }
	  else{ showError(numericValueNeeded)
	  return false;
	  }
  }
}

function validateWholeNumber(numberString){
    var strValidChars = "0123456789";
    var strChar;
    if (numberString.length == 0) {
        showError(invalidNumber);
        return false;
    } 
    if(numberString.length > 50){
        showError(numberDigitsExceeded);
        return false;
    }
    else{
        //  test strString consists of valid characters listed above
        for (i = 0; i < numberString.length; i++)
        {
            strChar = numberString.charAt(i);
            if(strValidChars.indexOf(strChar) == -1) {
				if (setMsgVar ==true)
				{
					 showError(invalidNumber);
				}
				return false;            	
			}
	    }
        return true;
    }
}

function validateWholeNumberField(field){
    //alert(field);
    var numberString = field.value;
//    if(numberString.length == 0) return true;//allow empty string
    removeError();
    removeMessage();
    var ret = validateWholeNumber(numberString);
    if(ret == false){
		field.value="";
		field.focus();
	}
    return ret;
}

function validateNumDaysBeforeDueDate(field, emailEnabled, smsEnabled){
    var numberString = field.value;
    removeError();
    removeMessage();
	if (!emailEnabled.checked && !smsEnabled.checked) return true;
	
    var ret = validateWholeNumber(numberString);
    if(ret == false){
		field.value="";
		field.focus();
	}
    return ret;
}

function validateNumberString(numberString){
    var strValidChars = "0123456789., ";
    var strChar;
    //alert(numberString);
    if (numberString.length == 0) {
        showError(invalidNumber);
        return false;
    } //allows empty string because it will be ignored}
    if(numberString.length > 50){
        showError(numberDigitsExceeded);
        return false;
    }
    else{
        //  test strString consists of valid characters listed above
        for (i = 0; i < numberString.length; i++)
        {
            strChar = numberString.charAt(i);
            if(strValidChars.indexOf(strChar) == -1 && numberString.length == 1) {
		if (setMsgVar ==true)
		{
		     showError(invalidNumber);
		}
	    	return false;            	
	    }
            if (strValidChars.indexOf(strChar) == -1 && !(i==0 && (strChar=='-' || strChar=='+'))){
			if (setMsgVar ==true)
				{
			     showError(invalidNumber);
				}

                return false;
            }
        }
        return true;
    }
}

//check whether the value of the field is a number
function validateNumberField(field){
    //alert(field);
    var numberString = field.value;
    if(numberString.length == 0) return true;//allow empty string
    removeError();
    removeMessage();
    var ret = validateNumberString(numberString);
    if(ret == false){
		field.value="";
		field.focus();
	}
    return ret;
}

//for Find Call page, and this method should be reconstructed with validateNumberField
function validateNumberFieldNonZero(field){
    var numberString = field.value;
    removeError();
    removeMessage();
    var ret = validateNumberString(numberString);
    if(ret == false){
		field.value="";
		field.focus();
	}
    return ret;
}

//Validate currency amount
function validateCurrency(field)
{
	var amount = field.value;
	if(amount.length == 0) return true;
	var pattern = /^((([1-9]\d*)|0)(\.\d{1,2})?)$/;
		if (pattern.test(amount)){
			return true;
		}else{
			showError(invalidNumber);
			field.value ="";
			return false;
		}
	
}

function validateVolumeField(field, usageType)
{
	if(usageType.value == 101)
	{
		return validateDurationField(field);
	}
	else if(usageType.value == 99 || usageType.value == 4 || usageType.value ==102)
	{
		return validateNumberField(field);
	}
}

function validateDurationField(field)
{
    var second;
    var minute;
    var hour;
    var value = field.value;
    var pos1 = value.indexOf(":");
    if(value.length==0) return true;
    if(pos1 < 0 ) {
        showError(invalidDurationFormat);
        field.focus();
        return false;
    }
    var pos2 = value.indexOf(":", pos1+1);
    if(pos2<0) {
        showError(invalidDurationFormat);
        field.focus();
        return false;
    }
    hour = value.substring(0,pos1);
    minute = value.substring(pos1+1, pos2);
    second = value.substring(pos2+1);
    if(!validateNumberString(hour)) {
        field.focus();
        return false;
    }
    if(!validateNumberString(minute)) {
        field.focus();
        return false;
    }
    if(!validateNumberString(second)) {
        field.focus();
        return false;
    }

}

function cleanupHiddenValues()
{
    var formElements = document.forms['reportForm'].elements;
    for (i=0; i<formElements.length; i++) {
        if (formElements[i].type == "hidden") {
            formElements[i].value = "";
        }
    }
}

function popup(url)
{
	showError('call popup method');
	newwindow=window.open(url,'name');
	if (window.focus) {newwindow.focus()}
	return false;
}

//Below method added for Dispute module

function popup(url, winX, winY, name) 
{
    if(navigator.appName == "Microsoft Internet Explorer") {
        screenY = winX;
        screenX = winY;
    } else {
        screenY = window.outerHeight-25;
        screenX = window.outerWidth-25;
    }
    leftPos = (screenX-winX);
    topPos = (screenY-winY);
	if(winX && winY)
	{
	   leftPos = (self.screen.width - winX)/2;
	   topPos =  (self.screen.height - winY)/2;
	   var settings = 	"toolbar=no,location=no,directories=no,"+
    					"status=yes,menubar=no,scrollbars=yes,"+
    					"resizable=yes,width="+winX+",height="+winY+
    					", left="+leftPos+", top="+topPos;
	}
	else
	{
	   leftPos = (self.screen.width - 700)/2;
	   topPos =  (self.screen.height - 600)/2;
       var settings = 	"toolbar=no,location=no,directories=no,"+
    					"status=yes,menubar=no,scrollbars=yes,"+
    					"resizable=yes,width=700,height=600,"+
    					"left="+leftPos+", top="+topPos;
    }   
	if(document.getElementById("accountId")&&document.getElementById("reportPeriodStart")&&document.getElementById("premiseKey")){
	  url+='&accountId='+document.getElementById("accountId").value+'&reportPeriodStart='+document.getElementById("reportPeriodStart").value+'&premiseKey='+document.getElementById("premiseKey").value;
	}
	
	
   	NewWindow=window.open(url,name,settings);
    	NewWindow.focus();
}

// This function added for "Pay Now" button to work in FireFox.
function getPayNowLink(){
 	window.location.href="${ctx}/${payment}/AnonymousPayment_create.action?action=create";
}

function getExternalLink(externalLink){
 	window.location.href=externalLink;
}

// This function is added for CR# 12-1JRHKHA
function validatePromptsDateFieldsOnSelect()
{
	var dtFrom=document.getElementById("reportPeriodStart").value;
	var dtTo=document.getElementById("reportPeriodEnd").value;

	 if(parseInt(dtFrom) > parseInt(dtTo)) {
        showError(invalidDateRange3)
        return false;
    }
	else return true

 }

var arr = [];
arr['JAN'] = 0;
arr['FEB'] = 1;
arr['MAR'] = 2;
arr['APR'] = 3;
arr['MAY'] = 4;
arr['JUN'] = 5;
arr['JUL'] = 6;
arr['AUG'] = 7;
arr['SEP'] = 8;
arr['OCT'] = 9;
arr['NOV'] = 10;
arr['DEC'] = 11;

// This function is added for CR# 12-1JZFED0
function isValidDate()
{
        var searchCitr = document.getElementById("searchCrit");
        var searchEntered = document.getElementById("searchEntered");
        
        if(searchEntered.value.length > 0 ) {
        
	    if (searchCitr.value == "1") 
		    {
			var arrTime = searchEntered.value.split(':');
			if(arrTime.length >1)
			{
				if(arrTime.length == 2 && searchEntered.value.length==5) 
				{
					var hrs = arrTime[0]
					var min = arrTime[1]
					if (hrs <=23 && min <=59) 
					{
						return true;
					}
					else 
					{
						removeError();
						showError(invalidTimeFormat)
						return false;
					}
				}
				else
				{  removeError();
					showError(invalidTimeFormat)
					return false;
				}
			}
			else 
			{   removeError();
				showError(invalidTimeFormat)
				return false;
			}
		}
		else if(searchCitr.value == "7" || searchCitr.value == "8")
		{
			if(isNaN(parseFloat(searchEntered.value)))
			{   removeError();
				showError(invalidNumber);
				return false;
			}
			else
				return true;
		}
	}
	
	return true;
 }

//This function is added to determine onkeypress is 'ENTER'
function isEventequalsENTER(event) 
{
	var keynum;
	if(window.event) // IE
	{
	  	keynum = event.keyCode;
	}
	else if(e.which) // Netscape/Firefox/Opera
	{
		  keynum = event.which;	  
	}
	if(keynum == 13){
		return true;
	} else {
		return false;
	}	
}

//This function is added to determine onkeypress is 'TAB'
function isEventequalsTAB(event) 
{
	var keynum;
	if(window.event) // IE
	{
	  	keynum = event.keyCode;
	}
	else if(e.which) // Netscape/Firefox/Opera
	{
		  keynum = event.which;	  
	}
	if(keynum == 9){
		return true;
	} else {
		return false;
	}	
}





//********************payment module scripts*********************************


//common cancel functions

function cancel(url){
	var action=url;
	document.forms[0].action=action;
	document.forms[0].submit();
}

function cancelform(form,url){
	var action=url;
	var formname=form;
	document.forms[formname].action=action;
	document.forms[formname].submit();
}

//common back funcions

function Back(url){
	var action=url;
	document.forms[0].action=action;
	document.forms[0].submit();
}

function Backform(form,url){
	var action=url;
	var formname=form;
	document.forms[formname].action=action;
	document.forms[formname].submit();
}

//common disablePayees()

//Multi DDN Support script
//function disablePayees(value,form) { 
    
//	var val=value;
//	var formname=form;
	//document.forms[formname].payeeAccount.disabled=val;
//}


//body_paymentaccount
function newBank() {
	document.forms[0].action="showCreateBankAccount.do";
	document.forms[0].submit();
} 

function newcc() {
	document.forms[0].action="showCreateCreditCardAccount.do";
	document.forms[0].submit();
}

//payment_addcc
	//cancel('showPaymentAccounts.do')

//payment_addBank
	//cancel('showPaymentAccounts.do')

//payment_editbank
	//cancel('showPaymentAccounts.do')
	
//payment_editcc
	//cancel('showPaymentAccounts.do')

//body_recurPmt
//function newRec() {
//  document.forms[0].action="showRecurringAccts.action";
//  document.forms[0].submit();
//}

//Payments_Recur_Setup
	//cancel('showrecurpmts.do')
	
//function newAccount() {
//	document.forms[0].action="/ebilling/payment/paymentReport_showAccounts.action";
//	document.forms[0].submit();
//}
// Scripts to populate payee account drop down.
//function BnkAccount(ddn,val,text)
//{
//	this.ddn = ddn;
//	this.id = val;
//	this.text = text;
//}
function countries(countrycd,statecd,statedesc)
{
	this.countrycd = countrycd;
	this.statecd = statecd;
	this.statedesc = statedesc;
}
function populateCountryList(src, dest){
	
	var ccd;
	var id;
	var desc;
	var i;
	
	i= 0;
	ccd = src.options[src.selectedIndex].value;	
	if (ccd != null && ccd.length>0){
		dest.options.length = 0;
		while (countryarray[src.selectedIndex-1][i]!=null){
			id = countryarray[src.selectedIndex-1][i].statecd;
			desc= countryarray[src.selectedIndex-1][i].statedesc;
			dest.options[i] = new Option(desc,id);
			i++;
	    }	    	
	}else{
		dest.options.length = 0;
		desc = src.options[src.selectedIndex].text;
		dest.options[0] = new Option(desc,'');
	}
}
	//disablePayees(document.setupReccrPaymentForm.accName.value.substring(0,5)=='ccard','setupReccrPaymentForm')
	
	//populatePayeeAcct(src, dest) is left in the jsp page since it contains scriptlets within scripts
	
/*function next_Payments_Recur_Setup() {						
	if(document.reportBody!=null){
		document.reportBody.accName.value=document.setupReccrPaymentForm.accName.value;
		document.reportBody.payee.value=document.setupReccrPaymentForm.payee.value;
		document.reportBody.payeeAccount.value=document.setupReccrPaymentForm.payeeAccount.value;
	}
	if(document.reportBody==null)
		alert(billingAccountsAlert)
	if(document.reportBody!=null)
		document.reportBody.submit();
} */

function next_Payments_Recur_Setup(billingAccountsAlert,errorType) {		
	if(document.forms['reportBody']!=null){
	    var paymentAccStatus = document.forms['setupReccrPaymentForm'].paymentAccountStatus;
		var radioVal = "";
		for (var i=0; i < paymentAccStatus.length; i++){
		    if(paymentAccStatus[i].checked == true){
			    radioVal = paymentAccStatus[i].value;
				break;
			}
		}
		document.forms['reportBody'].paymentAccountStatus.value=radioVal;
	    if (radioVal=="defaultAccount") {
		    document.forms['reportBody'].accName.value=document.forms['setupReccrPaymentForm'].accName.value;
		}
		if (radioVal=="existing") {
		    document.forms['reportBody'].accName.value=document.forms['setupReccrPaymentForm'].paymentAccount.value;
		}
	}
	if(document.forms['reportBody']==null)
		showError2(billingAccountsAlert,errorType)
	if(document.forms['reportBody']!=null)
		document.forms['reportBody'].submit();
}
//oneTimePaymentSelAcc

	//Backform('oneTimePaymentAccountform','onetimePay.do?page=showSelectBillingAccounts')

function getDate() {
//getting the current date in mm/dd/yyyy format.
	var currentDate = new Date();
	var year=currentDate.getYear()
	if (year < 1000)
		year+=1900
	var day=currentDate.getDay()
	var month=currentDate.getMonth()+1
	if (month<10)
		month="0"+month
	var day=currentDate.getDate()
	if (day<10)
		day="0"+day
	var today = month+"/"+day+"/"+year;
	return today;
}

function callPaymentAccountNameDisplay(chkBox,divID,divIDtwo,ele) {	
	var checked = chkBox.checked ;
	var divOne =  document.getElementById(divID);			
	var divTwo =  document.getElementById(divIDtwo);			
	if(checked==1){
		$("#"+divID).removeClass("displayNone");
		$("#"+divID).addClass("displayBlock");
		$("#"+divIDtwo).removeClass("displayNone");
		$("#"+divIDtwo).addClass("displayBlock");
     	chkBox.value='on';
		 document.forms['oneTimePaymentAccountform'].payDate.readOnly=false;
		 document.forms['oneTimePaymentAccountform'].payDate.style.background = "white";
		 $("#calendarpayDate").removeClass("displayNone");
		 $("#calendarpayDate").removeClass("displayBlock");		 
		 $("#calendarpayDate").addClass("displayInline");
	}else{
		$("#"+divID).removeClass("displayBlock");
		$("#"+divID).addClass("displayNone");
		$("#"+divIDtwo).removeClass("displayBlock");
		$("#"+divIDtwo).addClass("displayNone");
		 document.forms['oneTimePaymentAccountform'].payDate.value=document.forms['oneTimePaymentAccountform'].todayDate.value;
		 document.forms['oneTimePaymentAccountform'].payDate.readOnly=true;
		 document.forms['oneTimePaymentAccountform'].payDate.style.background = "#DBDBDB";
		ele.value="";
		 $("#calendarpayDate").removeClass("displayInline");
		 $("#calendarpayDate").removeClass("displayBlock");				
		$("#calendarpayDate").addClass("displayNone");
		//popup('oneTimePaymentPopup.do','530','200','OneTimeWarning');
	}					
}	

function callPmtAcctNameDefaultFlagDisplay(chkBox, divID, divIDtwo, ele, defaultFlag) {	
	var checked = chkBox.checked;
	var divOne =  document.getElementById(divID);			
	var divTwo =  document.getElementById(divIDtwo);			
	if(checked==1){
		$("#"+divID).removeClass("displayNone");
		$("#"+divID).addClass("displayBlock");
		$("#"+divIDtwo).removeClass("displayNone");
		$("#"+divIDtwo).addClass("displayBlock");
     	chkBox.value='on';
		 document.forms['oneTimePaymentAccountform'].payDate.readOnly=false;
		 document.forms['oneTimePaymentAccountform'].payDate.style.background = "white";
		 $("#calendarpayDate").removeClass("displayNone");
		 $("#calendarpayDate").removeClass("displayBlock");		 
		 $("#calendarpayDate").addClass("displayInline");
	}else{
		$("#"+divID).removeClass("displayBlock");
		$("#"+divID).addClass("displayNone");
		$("#"+divIDtwo).removeClass("displayBlock");
		$("#"+divIDtwo).addClass("displayNone");
		document.forms['oneTimePaymentAccountform'].payDate.value=document.forms['oneTimePaymentAccountform'].todayDate.value;
		document.forms['oneTimePaymentAccountform'].payDate.readOnly=true;
		document.forms['oneTimePaymentAccountform'].payDate.style.background = "#DBDBDB";
		ele.value="";
		$("#calendarpayDate").removeClass("displayInline");
		$("#calendarpayDate").removeClass("displayBlock");				
		$("#calendarpayDate").addClass("displayNone");
		if (!defaultFlag.disabled) {
		    defaultFlag.checked = 0;
		}
	}					
}


function showCreatePmtAccount(form,ele) {
	var srcElement = form.elements['newAccountType'].value;		
	var bankAccDiv =  document.getElementById('bankAccountNameDiv');			
	var bankAccDivOne =  document.getElementById('bankAccountNameDivOne');			
	var credCardAccDiv =  document.getElementById('creditAccountNameDiv');			
	var credCardAccDivOne =  document.getElementById('creditAccountNameDivOne');			
	var checkDiv =  document.getElementById('check');			
	var ccardDiv =  document.getElementById('ccard');	
	form.elements["isSave"].checked=0;
	$("#bankAccountNameDiv").removeClass("displayBlock");
	$("#bankAccountNameDiv").addClass("displayNone");
	$("#bankAccountNameDivOne").removeClass("displayBlock");
	$("#bankAccountNameDivOne").addClass("displayNone");
	form.elements["isCreditCardSave"].checked=0;
	$("#creditAccountNameDiv").removeClass("displayBlock");
	$("#creditAccountNameDiv").addClass("displayNone");
	$("#creditAccountNameDivOne").removeClass("displayBlock");
	$("#creditAccountNameDivOne").addClass("displayNone");	

	if(srcElement != '-1') {
		//var today = getDate();
		$("#popup").removeClass("displayBlock");
		$("#popup").addClass("displayNone");
		 document.forms['oneTimePaymentAccountform'].payDate.value=document.forms['oneTimePaymentAccountform'].todayDate.value;
		 document.forms['oneTimePaymentAccountform'].payDate.readOnly=true;
		 document.forms['oneTimePaymentAccountform'].payDate.style.background = "#DBDBDB"
		 $("#calendarpayDate").removeClass("displayInline");
		 $("#calendarpayDate").removeClass("displayBlock");
		 $("#calendarpayDate").addClass("displayNone");
		//popup('oneTimePaymentPopup.do','530','200','OneTimeWarning');
	}
    if(srcElement == 'check') 
	{
    	$("#popup").removeClass("displayNone");
    	$("#check").removeClass("displayNone");
    	$("#ccard").removeClass("displayBlock");
		
    	$("#popup").addClass("displayBlock");
    	$("#check").addClass("displayBlock");
    	$("#ccard").addClass("displayNone");
	   
    }
	if(srcElement=='ccard')
	{		
		$("#popup").removeClass("displayNone");
    	$("#check").removeClass("displayBlock");
    	$("#ccard").removeClass("displayNone");
		
    	$("#popup").addClass("displayBlock");
    	$("#ccard").addClass("displayBlock");
    	$("#check").addClass("displayNone");		
	   
    }
	if(srcElement=='-1')
	{
		$("#popup").removeClass("displayBlock");
		$("#ccard").removeClass("displayBlock");
		$("#check").removeClass("displayBlock");
		
    	$("#popup").addClass("displayNone");
    	$("#ccard").addClass("displayNone");
    	$("#check").addClass("displayNone");		
		   
	  document.forms['oneTimePaymentAccountform'].payDate.readOnly=false;
	  document.forms['oneTimePaymentAccountform'].payDate.style.background = "white"
	  

		$("#calendarpayDate").removeClass("displayBlock");
		$("#calendarpayDate").removeClass("displayNone");
	   $("#calendarpayDate").addClass("displayInline");	
	}
    return false;
}

function showSavedAccnt(form,ele) {		    
	var srcElement = form.elements['paymentSource'].value;				
	if(srcElement=='-1')
	{
		savedAccount.style.display='none';
	}else {				
		savedAccount.style.display='block';			   
	}			
    return false;
}


function forceSelect(form,value){
	$("#popup").removeClass("displayBlock");
	$("#popup").addClass("displayNone");	
	document.forms['oneTimePaymentAccountform'].payDate.readOnly=false;
	document.forms['oneTimePaymentAccountform'].payDate.style.background = "white"
	
	$("#calendarpayDate").removeClass("displayNone");
	$("#calendarpayDate").removeClass("displayBlock");
	$("#calendarpayDate").addClass("displayInline");
	var checkDiv =  document.getElementById('check');			
	var ccardDiv =  document.getElementById('ccard');
	var bankAcctDiv =  document.getElementById('bankAccount');			
	var ccardAcctDiv =  document.getElementById('ccardAccount');
	var noAcctDiv =  document.getElementById('noAccount');
	
	if(value=="defaultAccount")
	{
	  	selectCtl = form.elements["paymentSource"];
		selectCtl.value="-1";
		selectCtl.disabled=true;
		
		selectCtl = form.elements["newAccountType"];
		selectCtl.value="-1";
		selectCtl.disabled=true;
		
		$("#check").removeClass("displayBlock");
		$("#ccard").removeClass("displayBlock");
		$("#check").addClass("displayNone");
		$("#ccard").addClass("displayNone");
		
		$("#bankAccount").removeClass("displayBlock");
		$("#ccardAccount").removeClass("displayBlock");			
		$("#bankAccount").addClass("displayNone");
		$("#ccardAccount").addClass("displayNone")
		
		selectCtl = form.elements["defaultPmtAcctType"];
	    if(selectCtl.value!=null && selectCtl.value != "")
		{
			if(selectCtl.value=='check')
			{
				$("#bankAccount").removeClass("displayNone");
				$("#ccardAccount").removeClass("displayBlock");
				
				$("#bankAccount").addClass("displayBlock");
				$("#ccardAccount").addClass("displayNone");
			}
			if(selectCtl.value=='ccard')
			{
				$("#bankAccount").removeClass("displayBlock");
				$("#ccardAccount").removeClass("displayNone");
				
				$("#bankAccount").addClass("displayNone");
				$("#ccardAccount").addClass("displayBlock");
			}
		} else {
		    $("#bankAccount").removeClass("displayBlock");
			$("#ccardAccount").removeClass("displayBlock");
			$("#bankAccount").addClass("displayNone");
			$("#ccardAccount").addClass("displayNone");		
			$("#noAccount").removeClass("displayNone");
			$("#noAccount").addClass("displayBlock");
		}
	}
	
	if(value=="existing")
	{
		selectCtl = form.elements["paymentSource"];
		selectCtl.disabled=false;			
		selectCtl = form.elements["newAccountType"];
		selectCtl.value="-1";
		selectCtl.disabled=true;
		
		$("#check").removeClass("displayBlock");
		$("#ccard").removeClass("displayBlock");
		$("#bankAccount").removeClass("displayBlock");
		$("#ccardAccount").removeClass("displayBlock");
		$("#noAccount").removeClass("displayBlock");
		
		$("#check").addClass("displayNone");
		$("#ccard").addClass("displayNone");
		$("#bankAccount").addClass("displayNone");
		$("#ccardAccount").addClass("displayNone");
		$("#noAccount").addClass("displayNone");
	}
	if(value=="createNewAccount")
	{
		//savedAccount.style.display='none';
		selectCtl = form.elements["newAccountType"];
		selectCtl.disabled=false;
		selectCtl = form.elements["paymentSource"];
		selectCtl.value="-1";
		selectCtl.disabled=true;
		selectCtl = document.forms['oneTimePaymentAccountform'].elements["newAccountType"];
		
		$("#bankAccount").removeClass("displayBlock");
		$("#ccardAccount").removeClass("displayBlock");
		$("#noAccount").removeClass("displayBlock");
		
		$("#bankAccount").addClass("displayNone");
		$("#ccardAccount").addClass("displayNone");
		$("#noAccount").addClass("displayNone");
		
		if(selectCtl.value!=null)
		{
			if(selectCtl.value=='check')
			{
				$("#check").removeClass("displayNone");
				$("#ccard").removeClass("displayBlock");
				
				$("#check").addClass("displayBlock");
				$("#ccard").addClass("displayNone");
			}
			if(selectCtl.value=='ccard')
			{
				$("#check").removeClass("displayBlock");
				$("#ccard").removeClass("displayNone");
				
				$("#check").addClass("displayNone");
				$("#ccard").addClass("displayBlock");
			}
			if(selectCtl.value=='-1')
			{
				$("#check").removeClass("displayBlock");
				$("#ccard").removeClass("displayBlock");
				
				$("#check").addClass("displayNone");
				$("#ccard").addClass("displayNone");
			}
		}
	}
}


function forceRecurSelect(form,value){
	var bankAcctDiv =  document.getElementById('bankAccount');			
	var ccardAcctDiv =  document.getElementById('ccardAccount');
	var noAcctDiv =  document.getElementById('noAccount');
	
	if(value=="defaultAccount")
	{
	  	selectCtl = form.elements["paymentAccount"];
		selectCtl.value="";
		selectCtl.disabled=true;
		
		$("#bankAccount").removeClass("displayBlock");
		$("#ccardAccount").removeClass("displayBlock");			
		$("#bankAccount").addClass("displayNone");
		$("#ccardAccount").addClass("displayNone")
		
		selectCtl = form.elements["defaultPmtAcctType"];
	    if(selectCtl.value!=null && selectCtl.value != "")
		{
			if(selectCtl.value=='check')
			{
				$("#bankAccount").removeClass("displayNone");
				$("#ccardAccount").removeClass("displayBlock");
				
				$("#bankAccount").addClass("displayBlock");
				$("#ccardAccount").addClass("displayNone");
			}
			if(selectCtl.value=='ccard')
			{
				$("#bankAccount").removeClass("displayBlock");
				$("#ccardAccount").removeClass("displayNone");
				
				$("#bankAccount").addClass("displayNone");
				$("#ccardAccount").addClass("displayBlock");
			}
		} else {
		    $("#bankAccount").removeClass("displayBlock");
			$("#ccardAccount").removeClass("displayBlock");
			$("#bankAccount").addClass("displayNone");
			$("#ccardAccount").addClass("displayNone");		
			$("#noAccount").removeClass("displayNone");
			$("#noAccount").addClass("displayBlock");
		}
	}
	
	if(value=="existing")
	{
		selectCtl = form.elements["paymentAccount"];
		selectCtl.disabled=false;			
		
		$("#bankAccount").removeClass("displayBlock");
		$("#ccardAccount").removeClass("displayBlock");
		$("#noAccount").removeClass("displayBlock");
		
		$("#bankAccount").addClass("displayNone");
		$("#ccardAccount").addClass("displayNone");
		$("#noAccount").addClass("displayNone");
	}
}

function disableRadioButton()
{
  if(document.getElementById("check") != null) {  /*  this condition was added to work only with onetiimepaymentSelAcc */

    radioCtl = document.forms['oneTimePaymentAccountform'].elements["paymentAccountStatus"];				
	selectCtl = document.forms['oneTimePaymentAccountform'].elements["newAccountType"];	
	selectCtl2 = document.forms['oneTimePaymentAccountform'].elements["paymentSource"];				
	var checkDiv =  document.getElementById('check');			
	var ccardDiv =  document.getElementById('ccard');	
	var radioButtonValue = null;
	if(radioCtl[0].checked) {
		radioButtonValue=radioCtl[0].value;
	}else {
		radioButtonValue=radioCtl[1].value;	
	}
	if(radioButtonValue=='createNewAccount')
	{	
		var temp = selectCtl.value;
		if(temp=="check" || temp=="ccard")
		{
			if(selectCtl.value=='check')
			{  
			   $("#check").removeClass("displayNone");
			   $("#ccard").removeClass("displayBlock");
			   
			   $("#check").addClass("displayBlock");
			   $("#ccard").addClass("displayNone");
			}
			if(selectCtl.value=='ccard')
			{
			   $("#check").removeClass("displayBlock");
			   $("#ccard").removeClass("displayNone");
			   
			   $("#check").addClass("displayNone");
			   $("#ccard").addClass("displayBlock");			   
			}
			selectCtl.disabled=false;
			selectCtl2.disabled=true;
			var isSaveValue = document.forms['oneTimePaymentAccountform'].isSave.value;
			var isCredValue = document.forms['oneTimePaymentAccountform'].isCreditCardSave.value;
			if( (isSaveValue=='on' && isCredValue=='') || (isSaveValue=='' && isCredValue=='on') || (isSaveValue=='on' && isCredValue=='on') ) {
				document.forms['oneTimePaymentAccountform'].isSave.checked=true;
				document.forms['oneTimePaymentAccountform'].isCreditCardSave.checked=true;
				document.forms['oneTimePaymentAccountform'].payDate.readOnly=false;			
				document.forms['oneTimePaymentAccountform'].payDate.style.background = "white";
				$("#calendarpayDate").removeClass("displayBlock");
				$("#calendarpayDate").removeClass("displayNone");
				$("#calendarpayDate").addClass("displayInline");
			} else {
				document.forms['oneTimePaymentAccountform'].isSave.checked=false;
				document.forms['oneTimePaymentAccountform'].isCreditCardSave.checked=false;
				document.forms['oneTimePaymentAccountform'].payDate.value=document.forms['oneTimePaymentAccountform'].todayDate.value;
				document.forms['oneTimePaymentAccountform'].payDate.readOnly=true;		
				document.forms['oneTimePaymentAccountform'].payDate.style.background = "#DBDBDB";
				$("#calendarpayDate").removeClass("displayBlock");
				$("#calendarpayDate").removeClass("displayInline");
				$("#calendarpayDate").addClass("displayNone");
			}
	  	}
	}else if(selectCtl.value=='-1' && radioButtonValue=='existing' ) {					   
		   selectCtl.disabled=true;
		   selectCtl2.disabled=false;
		   $("#check").removeClass("displayBlock");
		   $("#ccard").removeClass("displayBlock");
		   
		   $("#check").addClass("displayNone");
		   $("#ccard").addClass("displayNone");
		   radioCtl[0].checked=true;
	}	
	temp="";
	if(selectCtl2.value!=-1){
	temp = selectCtl2.value.substring(0,5);
	}
	if(temp=="check" || temp=="ccard")
	{
	    selectCtl.disabled=true;
	   selectCtl2.disabled=false;				  	   		   
	}else if(selectCtl2.value=='-1' && radioButtonValue=='createNewAccount') {
	   selectCtl.disabled=false;
	   selectCtl2.disabled=true;
	   radioCtl[1].checked=true;
	}
 
   }
} 

	//cancelform('oneTimePaymentAccountform','onetimePay.do?rptAction=keepValue&transformerId=tr1&columnId=checkbox&value=true')
	//disablePayees(document.oneTimePaymentAccountform.paymentSource.value.substring(0,5)=='ccard','oneTimePaymentAccountform')
	//BnkAccount(ddn,val,text)
	//populatePayeeAcct(src, dest) is left in the jsp page since it contains scriptlets within scripts

function next_oneTimePaymentSelAcc(){				
	document.forms['oneTimePaymentAccountform'].submit();
	document.forms['oneTimePaymentAccountform'].submits.disabled=true;
}

function disable_onTimePaymentSubmit() {
    document.forms['oneTimePaymentAccountform'].submits.disabled=true;
}

function disable_oneTimePmtTransactionSubmit(formName) {
	document.forms[formName].submit();
    document.forms[formName].submits.disabled=true;
}

//cancelOneTimePayment
	//cancelform('cancelForm','./showPaymentActivity.do')
function submit() {
	document.forms['cancelForm'].action="./cancelOneTimePayment.do";
	document.forms['cancelForm'].submit();
}

//onetimeCancelConfirmation
	//Back('./showPaymentActivity.do')

//editOneTimePaymentRec
	//cancelform('oneTimePaymentAccountform','./showPaymentActivity.do')

//confirmEditOneTimePaymentRec
	//cancelform('oneTimePaymentAccountform','./showPaymentActivity.do') 

//header_payment
function fnPopup(url)
{
	var x="600";
	var y="550";
	popup(url,x,y);
}
	
	
//payment_confirmbankacc
	//cancel('showPaymentAccounts.do')

//payment_confirmcreditcardacc
	//cancel('showPaymentAccounts.do')

//Payments_Recur_Options
	//cancel('showrecuracts.do')
	
function disableElement(element,val) { 
    document.getElementById(element).disabled=val;
}

//Payments_Recur_Edit_Summary
	//cancel('showrecurpmts.do')
	
//confirmEditOneTimePayment
	//cancelform('oneTimePaymentAccountform','showPaymentActivity.do')
function submitCon() {
	document.forms['oneTimePaymentAccountform'].submit();
	document.forms['oneTimePaymentAccountform'].Confirm1.disabled=true;
}

//confirmOneTimePayment
	//cancelform('oneTimePaymentAccountform','onetimePay.do')
	//submitCon()

//dueAmountWarning
	//Backform('dueamountWarningPage','onetimePay.do?page=showSelectBillingAccounts')

//editDueAmountWarning
	//Backform('dueamountEditWarningPage','editOneTimePaymentPage.do')

//onetimeUpdateConfirmation
	//Back('./showPaymentActivity.do')
	
//Payment_RecurCancel
	//cancel('showrecurpmts.do')
	
//Payments_Recur_Confirm
	//cancel('showrecurpmts.do')

//recurringPaymentWarning
	//Backform('OneTimePaymentWarningPage','onetimePay.do')

//Payments_Recur_Due_Edit
	//cancel('showrecurpmts.do')
	//disablePayees(document.recurringPaymentform.paymentAccount.value.substring(0,5)=='ccard','recurringPaymentform')
	//disableElement(element,val)
	
function enableElement(element,val) { 
    document.getElementById(element).disabled =val;
}//no function calls to this function in the jsp page - not tested

function enableRadioButton()
 {
   selectCtl = document.forms['recurringPaymentform'].elements["transferDate"];
   selectCtl.enabled=true;
 }//no function calls to this function in the jsp page - not teted

function callSubmit() {
	document.forms[0].action="confirmEditRecurpmts.action?action=confirm";
	
	document.forms[0].submit();
}

function createPaymentAccount() {
	document.forms[0].action="/ebilling/payment/paymentReport_showAccounts.action";
	document.forms[0].submit();
}
	//BnkAccount(ddn,val,text)
	//populatePayeeAcct(src, dest) is left in the jsp page since it contains scriptlets within scripts

	
function selectAll(colId, status, groupKey){
	formName = "form_checkAll";
	form = document.forms[formName];      
	form.checkAll_colId.value=colId;      
	form.checkAll_status.value = status;      
	form.currentGroup.value=groupKey;      
	reportId=form.checkAll_reportId.value;
	transformId=form.checkAll_transformerId.value;
	reportBodyDivId = "div#report_body_" + reportId + "_" + transformId;
	ajaxLoadForForm(formName, reportBodyDivId);
}



function populatePayeeAcct(src, dest ,len){
			
var ddn;
var id;
var desc;
var i;
var j;
var arrayLen=len;
				
j = 0;
ddn = src.options[src.selectedIndex].value;
				
if (ddn != '0'){
    dest.options.length = 0;
	for (i=0; i<arrayLen; i++){
		if(ddn == Array[i].ddn){   
		  id = Array[i].id;
		  desc= Array[i].text;
		  dest.options[j] = new Option(desc,id);
		  j = j +1;
		}
	}
}
				
}

// This method was added to replace &amp; with & in the editOnteTimePayment.do form action.

function returnUrl(arg){

  var x=arg.replace('&amp;','&');
  var y=x.replace('&amp;','&');
  var z=y.replace('&amp;','&');
  
  return z; 

}

// method for Payment_RecurCancel   cancel  button 
function cancelRecur(){
     	document.forms[0].action="showRecurringPayments.action";
	document.forms[0].submit();
}

 
 /*************************** report_body ***********************/
 
   function setCellInput( element1,  element2, status){

       element1.value=status;

       element2.value=status;

   }

  function setCellInputNew(pagingFormName1,pagingFormName2,radioKey,status){
 		if(navigator.userAgent.toLowerCase().indexOf('chrome') > -1){
		var sucobjs=$("input[type='hidden'][name='"+radioKey+"']");
		sucobjs.attr("value",status);
		return;
		}   
		var pagingForm1=document.forms[pagingFormName1];
		var pagingForm2=document.forms[pagingFormName2];
		if(pagingForm1){
			var str1 ="document.forms['"+pagingFormName1+"']."+radioKey+".value = '"+status+"';";
			eval(str1);
		}
		if(pagingForm2){
			var str2 = "document.forms['"+pagingFormName2+"']."+radioKey+".value = '"+status+"';";
			eval(str2);
		}
 }

  function setCellInputNewWithoutPaging(formName,radioKey,status){
		if(navigator.userAgent.toLowerCase().indexOf('chrome') > -1){
		var sucobjs=$("input[type='hidden'][name='"+radioKey+"']");
		sucobjs.attr("value",status);
		return;
		}   
		var pagingForm=document.forms[formName];
		if(pagingForm){
			var str1 ="document.forms['"+formName+"']."+radioKey+".value = '"+status+"';";
			eval(str1);
		}
}

   function getLink(url) {

var selectedValue = document.getElementById("reportPeriodStart").value;

var nextValue = selectedValue - getDifference();

location.href = url+nextValue;

   }



 function getDifference() { 
 var selectValue = document.getElementById("reportPeriodStart").value; 
 var temp=selectValue; 
 for(i=0;i<document.getElementById("reportPeriodStart").length;i++) 
 { 	    
	temp = document.getElementById("reportPeriodStart").options[i].value; 	    
	if(selectValue==temp){ 	   
		if(i < document.getElementById("reportPeriodStart").length-1){
			temp = document.getElementById("reportPeriodStart").options[i+1].value; 
			if(temp < selectValue){
				return selectValue-temp;
			}
			else if(i>0){
				temp = document.getElementById("reportPeriodStart").options[i-1].value; 
				if(temp < selectValue){
					return selectValue-temp;
				}
			}
		}
		break;  
	} 	   
 } 
 return 0;
 }   

function disableAnchor(obj, disable){

if(disable){

	var href = obj.getAttribute("href");

		if(href && href != "" && href != null){

			obj.setAttribute('href_bak', href);

		}

		obj.removeAttribute('href');

		obj.style.color="gray";

}

}



   function validatePreviousLink(){

	var selectValue = document.getElementById("reportPeriodStart").value;

	var temp=selectValue;

	for(i=0;i<document.getElementById("reportPeriodStart").length;i++) {

	    var temp1 = document.getElementById("reportPeriodStart").options[i].value;

	    if(i==0){

	        temp=temp1;

	    }else{

	        if(temp>temp1){

	            temp=temp1

	        }

	    }

	}

	if(selectValue==temp){

    		disableAnchor(document.getElementById("href_id"),true);

	}

   return true;

  }
  
  
/*This js function belongs to the paging file in reporting\src\emplate\common\reporting*/  
  
function check_fetchBoundary(form)
{
var dispConfirm=false;
for(var i = 0; i < form.elements.length; i++)
{	
	if(form.elements[i].name.indexOf('cell_') == 0){	
	if (form.elements[i].value=="true")
	{
		dispConfirm=true;
		break;
	}
	}
		
}
if (dispConfirm==true)
{
	return confirm("Continuing to the selected page will result in loosing your current selections.");	
	
}
else
{
	if ($transformer.isSelectedInCurrentFetch())
	return confirm("Continuing to the selected page will result in loosing your current selections.");	
	end
	return true;
}
}

function getMoreTreeNodes(trNodeId, node, parentNode, reportId, treeId, contentReportId){
	if(reportId == "statementGroupReport"){
		myurl = "statement.do";
	}
	else if(reportId == "telco_std_r20"){
		myurl = "report.do";
	}
	var nodeId = node.replace(/[^a-zA-Z 0-9]/g,'t');
	var periodStart=document.getElementById("reportPeriodStart").value;
	var periodEnd=document.getElementById("reportPeriodEnd").value;
	var selectData = "stepAction=select&reportId="+reportId+"&contentReportId="+contentReportId+"&treeId="+treeId+"&nodeId="+node+"&parentNodeId="+parentNode+"&reportPeriodStart="+periodStart+"&reportPeriodEnd="+periodEnd;
	var prefix=trNodeId.replace(nodeId, "");
	var siblings="tr[id^="+prefix+"]";
	$.ajax({type:"POST", data:selectData, url:myurl, success:function(html){
		if(html.indexOf('j_username') > 1){
			window.location = "login.do";
		}
		$(siblings).remove();
		var parentTrId = trNodeId.replace("tr"+nodeId, "");
		$("tr#"+parentTrId).after(html);
		stripeTable($('table.rpt'));
	}}); 
	
}
function toggleStatementTree(trNodeId, node, reportId, treeId, contentReportId){
    
	//disable the link to avoid duplicated ajax request,will enable this link after request is done
	var hreflink=$('tr#'+trNodeId+' td a:first').attr('href');
	$('tr#'+trNodeId+' td a:first').attr('href','javascript:void(0);');
	
	if(reportId == "statementGroupReport"){
		myurl = "statement.action";
	}
	else if(reportId == "telco_std_r20"){
		myurl = "report.action";
	}
	var nodeId = node.replace(/[^a-zA-Z 0-9]/g,'t');

	if($("img#img"+node).attr("alt").split(" ").length>2){
		var nodeTitle=$("img#img"+node).attr("alt").split(" ")[1]+' '+$("img#img"+node).attr("alt").split(" ")[2];
	}
	else{
		if($("img#img"+node).attr("alt").split(" ").length>1){
		var nodeTitle=$("img#img"+node).attr("alt").split(" ")[1]
		}
	}
	var periodStart=document.getElementById("reportPeriodStart").value;
	var periodEnd=document.getElementById("reportPeriodEnd").value;
	
	if(parseInt(periodStart)>parseInt(periodEnd)){
		showError(invalidDateRange2);
		return;
	}
	removeError();
	var costRealloc=false;
	if(document.forms['reportForm'].costReallocOn)
	{
		for (var i=0; i < document.forms['reportForm'].costReallocOn.length; i++)
		{
			if (document.forms['reportForm'].costReallocOn[i].checked)
			{
				costRealloc = document.forms['reportForm'].costReallocOn[i].value;
			}
		}
	}
	expandData = "stepAction=expand&reportId="+reportId+"&contentReportId="+contentReportId+"&treeId="+treeId+"&nodeId="+node+"&reportPeriodStart="+periodStart+"&reportPeriodEnd="+periodEnd+"&costReallocOn="+costRealloc;

	replaceImage(nodeId, '../_assets/images/loading_spinner.gif', spinIconLabel);
	var prefix=trNodeId+"tr";
	var children = "tr[id^="+prefix+"]";
	if($('tr#'+trNodeId).next().attr('id')==null || $('tr#'+trNodeId).next().attr('id').indexOf(trNodeId) != 0){
			//node is empty, need to go to server for content
			$.ajax({type:"GET", data:expandData, url:myurl, success:function(html){
				if(html.indexOf('j_username') > 1){
					window.location = "../nonAuth/login.action";
				}
				$('tr#'+trNodeId).after(html);
				replaceImage(nodeId, '../_assets/images/collapse.gif',collapseIconLabel+" "+nodeTitle);
				stripeTable($('table.rpt'));
				$('tr#'+trNodeId+' td a:first').attr('href',hreflink);
				$('#statusInformation').remove();
				$("<div id='statusInformation' role='alert' class='hiddenReadableElement'>" + expandedMessage + "</div>").insertBefore("table.rpt");
			}});
		}else if($('tr#'+trNodeId).next().attr("style")==null || $('tr#'+trNodeId).next().attr("style").toLowerCase().indexOf("display: none")==-1){//is(':visible')){
			//node is full, hide and let server know user collapsed it
			$(children).hide();
			$(children).each(function(){
				$(this).attr("collapsed",function(){
					return $(this).attr("collapsed") + nodeId;
				});
			});
			replaceImage(nodeId, '../_assets/images/expand.gif', expandIconLabel+" "+nodeTitle);
			stripeTable($('table.rpt'));
			$('tr#'+trNodeId+' td a:first').attr('href',hreflink);
			$('#statusInformation').remove();
			$("<div id='statusInformation' role='alert' class='hiddenReadableElement'>" +  collapsedMessage  + "</div>").insertBefore("table.rpt");
		}else{
			//node is full, show and let server know user expanded it
			children = "tr[id^="+prefix+"][collapsed^="+nodeId+"]";
			$(children).show();
			children = "tr[id^="+prefix+"]";
			$(children).each(function(){
				$(this).attr("collapsed", function(){
					return $(this).attr("collapsed").replace(nodeId, "");
				});
			});
			replaceImage(nodeId, '../_assets/images/collapse.gif', collapseIconLabel+" "+nodeTitle);
			stripeTable($('table.rpt'));
			$('tr#'+trNodeId+' td a:first').attr('href',hreflink);
			$('#statusInformation').remove();
			$("<div id='statusInformation' role='alert' class='hiddenReadableElement'>" + expandedMessage + "</div>").insertBefore("table.rpt");
		}
	
}

function replaceImage(nodeId, image, alt){
	var imageID = "img#img" + nodeId;
	$(imageID).attr("src",image);
	$(imageID).attr("alt",alt);
	replaceImageAlt();
}

function replaceImageAlt(){
	$("div[class='contentbox'] img[id^=img]").each(function(){
	if($(this).attr("alt").split(" ").length<2){
	var nodeImgText=$.trim($(this).parent().parent().text());
	$(this).attr('alt',$(this).attr('alt')+' '+nodeImgText);
	var nodeDetail=$.trim($(this).parent().parent().next().text());
	if(nodeDetail){
		$(this).attr('alt',$(this).attr('alt')+' '+nodeDetail);
	}
	}
	});
	}

function stripeTable(table) { 
	$("tr:visible:even", table).removeClass("even").addClass("odd"); 
	$("tr:visible:odd", table).removeClass("odd").addClass("even"); 
}

function WinOpen(formname) {
  var url=document.forms[formname].format.value;
  window.location.href=url;

}

function WindowOpen(formname, reportId, isThresholdExceeded, isXMLThresholdExceeded, isPDFThresholdExceeded){
	var url="batch.action?reportId="+reportId+"&batchAction=create&tab=batch";
	var value=document.forms[formname].format.value;
	var iStart = value.indexOf("type=") + 5;
	var iEnd = value.indexOf("&templateId=");
	var type = value.substring(iStart,iEnd);
	if(type == "csv"){
		if(isThresholdExceeded=="true"){
			alert(maxRowsExceededDownload);
		}
		else{
			url = document.forms[formname].format.value;
		}
	}
	else if(type == "xml"){
		if(isXMLThresholdExceeded=="true"){
			alert(maxRowsExceededDownload);
		}
		else{
			url = document.forms[formname].format.value;
		}
	}
	else if(type == "pdf"){
		if(isPDFThresholdExceeded=="true"){
			alert(maxRowsExceededDownload);
		}
		else{
			url = document.forms[formname].format.value;
		}
	}
			window.location.href=url;
}

function showError(errorMsg){
	var errorHtml = "<div class=\"errormessage\" id=\"errormessage\"><h4>"+errorDisplayed+"</h4><div class=\"erroricon\"></div>"+errorMsg+"</div>";
	var msg = $("div.errormessage").text();
	if(msg.indexOf(errorMsg)==-1){
		if($("div#pageheading + div").hasClass("pagetabs")){
				$("div.pagetabs").after(errorHtml);
			}
		else{
			$("div#pageheading").after(errorHtml);
		}
	}
	$("div.errormessage").attr("tabindex","0");
	$("div.errormessage")[0].focus();
	$("div.errormessage").find("div[class='erroricon']").html("<img alt='' src='../_assets/skin/error.gif'/>");
	setFocusOnForm();
}

function showError2(errorMsg,errorType){
	var errorHtml = "<div class=\"errormessage\" id=\"errormessage\"><h4>"+errorType+"</h4><div class=\"erroricon\"></div>"+errorMsg+"</div>";
	var msg = $("div.errormessage").text();
	if(msg.indexOf(errorMsg)==-1){
		if($("div#pageheading + div").hasClass("pagetabs")){
				$("div.pagetabs").after(errorHtml);
			}
		else{
			$("div#pageheading").after(errorHtml);
		}
	}
	$("div.errormessage").attr("tabindex","0");
	$("div.errormessage")[0].focus();
	$("div.errormessage").find("div[class='erroricon']").html("<img alt='' src='../_assets/skin/error.gif'/>");
	setFocusOnForm();
}
/* Remove error message without refresh the page */
function removeError(){
	if($("div#pageheading + div").hasClass("pagetabs")){
			$("div.pagetabs ~ div.errormessage").remove();
		}
	else{
		$("div#pageheading ~ div.errormessage").remove();
	}
	
	//fix Bug 16444940, this line can remove both struts and js validation error messages
	$("div#breadcrumb ~ div.errormessage").remove();
}

/* Remove success message without refresh the page */
function removeMessage(){
	if($("div#pageheading + div").hasClass("pagetabs")){
			$("div.pagetabs ~ div.successmessage").remove();
		}
	else{
		$("div#pageheading ~ div.successmessage").remove();
	}
}
/* This fuction trims the text input of the form in order to feed the validation need */
/* Upadte for CR 12-1YNKTQD and could be used for all of the forms whose elements need to be trimed */
function trimInput(form){
	var formLength = form.length;
	var iterator = 0;
	var tempString;
	
	for(; iterator < formLength ; iterator ++){
		if(form.elements[iterator].type == 'text'){
			tempString = $.trim(form.elements[iterator].value);
			form.elements[iterator].value = tempString;
		}
	}
}

function getClientTimeZone()
{
	var current_date = new Date( );
	var rightNow = new Date();
    var toDay = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);
    var temp = toDay.toGMTString();
    var date2 = new Date(temp.substring(0, temp.lastIndexOf(" ") -1));
    var stdTime = (toDay - date2) / (1000 * 60 * 60);

    if(stdTime <= 0)
		document.forms['oneTimePaymentAccountform'].elements["cliTimeZone"].value = "GMT" + stdTime;
    else
		document.forms['oneTimePaymentAccountform'].elements["cliTimeZone"].value = "GMT+" + stdTime;
    document.forms['oneTimePaymentAccountform'].submit();
}

/*
 * ajax load by submitting form
 */
function ajaxLoadForForm(reportFormName, target){
	// set form
	formId = '#' + reportFormName;
	// set target element id
	targetId = target;

    var options = {
        beforeSubmit:  ajaxLoadRequest,  // pre-submit callback
        success:       ajaxLoadResponse  // post-submit callback

        // other available options:
        //target:    null        // target element(s) to be updated with server response
        //url:       url         // override for form's 'action' attribute
        //type:      type        // 'get' or 'post', override for form's 'method' attribute
        //dataType:  null        // 'xml', 'script', or 'json' (expected server response type)
        //clearForm: true        // clear all form fields after successful submit
        //resetForm: true        // reset the form after successful submit

        // $.ajax options can be used here too, for example:
        //timeout:   3000
    };

    // ajax form request
    $(formId).ajaxSubmit(options);

}

/*
 * ajax load pre-submit callback
 */
function ajaxLoadRequest(formData, jqForm, options) { 
	// formData is an array; here we use $.param to convert it to a string to display it 
	// but the form plugin does this for you automatically when it submits the data 
	// var queryString = $.param(formData);
	
	// jqForm is a jQuery object encapsulating the form element.  To access the 
	// DOM element for the form do this: 
	// var formElement = jqForm[0];
	
	// TODO: add code here if need pre-submit processing
	
	// here we could return false to prevent the form from being submitted; 
	// returning anything other than false will allow the form submit to continue 
	return true;
} 

/*
 * ajax load post-submit callback 
 */
function ajaxLoadResponse(responseText, statusText, xhr, $form)  { 
	// for normal html responses, the first argument to the success callback 
	// is the XMLHttpRequest object's responseText property 
	
	// if the ajaxForm method was passed an Options Object with the dataType 
	// property set to 'xml' then the first argument to the success callback 
	// is the XMLHttpRequest object's responseXML property 
	
	// if the ajaxForm method was passed an Options Object with the dataType 
	// property set to 'json' then the first argument to the success callback 
	// is the json data object returned by the server 
	
	// force user to login page if session timeout
	if (!ajaxRequestSessionTimeout(responseText)){
		// clean up error message
		removeError();
		
		// in case the responseText is not XML like, which is jQuery required for analyzing
		wrappedResponseText = "<div id='responseTextWrapperDiv'>" + responseText + "</div>";
		
		// refresh taget report body div
		$(targetId).html($(wrappedResponseText).find(targetId).html());
		// add the page information for ada
		var currentPageValue = $(wrappedResponseText).find('.pagingbar > input[name=pageNavigation]');
		var table = $(targetId).find('.contentbox .rpt');
		if(table[0] && currentPageValue[0]) {
            var pageHeadermarker = "<div id='pageInformation' role='alert' class='hiddenReadableElement'><h4>Navigated to page " + $(currentPageValue).val() + "</h4></div>";
			
			$(pageHeadermarker).insertBefore(table);
			setTimeout(function(){$('.pagingbar > input[name=pageNavigation]:first').focus();}, 0);
			
		}
		if(table[0]){
			var checkAllTemp = table.find("input[type='checkbox']").first();
			if(checkAllTemp[0] && checkAllTemp.attr('onclick').indexOf('selectAll')>=0)
				setTimeout(function(){checkAllTemp.focus();}, 0);
		}
	}
}

/*
 * paging in ajax way
 */
function ajaxReportPaging(reportFormName, action){
	// set form
	rptPagingForm = document.forms[reportFormName];
	rptPagingForm.pagingAction.value = action;
		
	// get report and transformer id from form
	reportId = rptPagingForm.reportId.value;
	transformerId = rptPagingForm.transformerId.value;
	
	// target
	reportBodyDivId = 'div#report_body_' + reportId + '_' + transformerId;
	ajaxLoadForForm(reportFormName, reportBodyDivId);
}

/*
 * load report body in ajax way in specifying page
 */
function ajaxReportPageSelect(event, transformerId, pagingNavCount, maxPageNumberInCurrentBatch){
	// get pressed key code
	var keyCode = event.which;
	if (keyCode == undefined) {
		keyCode = event.keyCode;
	}
	
	// 'Enter' to submit
	if (keyCode == 13){
		// validate input page number
		var pageInputTextId = 'pageEntry_' + transformerId + '_' + pagingNavCount;
		setTimeout(function(){
           if(checkPageNumber(pageInputTextId, maxPageNumberInCurrentBatch) != false ){
			    // ajax form submit
			    var reportFormName = transformerId + '_pagingForm' + pagingNavCount;
			    ajaxReportPaging(reportFormName, 'submit');
		    } else {
		        event.preventDefault();
		        return false;
		    }
        },0);

	}

	// return false because no need to submit the form in normal way
	return false;
}


/*
 * load page in ajax way for link <a> tag
 
function ajaxLoadForLink(url, target,tabobj,ascending,sortmessage){

	// load the page of url and update target element in ajax way
	$.ajax({
		url: url,
		cache: false,
		success: function(responseText){
			// force user to login page if session timeout
			if(!ajaxRequestSessionTimeout(responseText)){
				// clean up error message
				removeError();
				// in case the responseText is not XML like, which is jQuery required for analyzing
				wrappedResponseText = "<div id='responseTextWrapperDiv'>" + responseText + "</div>";
				$(target).html($(wrappedResponseText).find(target).html());
				if("true"==ascending){
				$(target).find(tabobj).find('a').find('img').attr('title',sortmessage+$(target).find(tabobj).find('a').find('img').attr('title')).attr('alt',sortmessage+$(target).find(tabobj).find('a').find('img').attr('alt'));
				$(target).find(tabobj).attr('class',$(target).find(tabobj).attr('class')+' '+'sortasc');
				$(target).find(tabobj).find('a').focus();
				}else{
				$(target).find(tabobj).find('a').find('img').attr('title',sortmessage+$(target).find(tabobj).find('a').find('img').attr('title')).attr('alt',sortmessage+$(target).find(tabobj).find('a').find('img').attr('alt'));
				$(target).find(tabobj).attr('class',$(target).find(tabobj).attr('class')+' '+'sortdesc');
				$(target).find(tabobj).find('a').focus();
				}
			}
		}
	});
	// do not fire request when click the link tag
	//return false;
}
*/

function ajaxLoadForLink(url, target,tabobj,ascending,sortmessage,formID){

	// set form
	var formId = '#' + formID;
	if($(formId).length>0){
		// prepare the form when the DOM is ready 
		$(formId).ready(function() { 
			var options = {
				beforeSubmit:  ajaxLoadRequest,  // pre-submit callback
				success:       function(responseText){
				// force user to login page if session timeout
				if(!ajaxRequestSessionTimeout(responseText)){
					// clean up error message
					removeError();
					// in case the responseText is not XML like, which is jQuery required for analyzing
					wrappedResponseText = "<div id='responseTextWrapperDiv'>" + responseText + "</div>";
					prompts=$(target).find(".prompts:first");
					var content=$(prompts).html();
					$(target).html($(wrappedResponseText).find(target).html());
					report = $(target).find(".contentbox:first");
					$(prompts).html(content).prependTo(report);
					if("true"==ascending){
					$(target).find(tabobj).find('a').find('img').attr('title',sortmessage+$(target).find(tabobj).find('a').find('img').attr('title')).attr('alt',sortmessage+$(target).find(tabobj).find('a').find('img').attr('alt'));
					$(target).find(tabobj).attr('class',$(target).find(tabobj).attr('class')+' '+'sortasc');
					$(target).find(tabobj).find('a').focus();
					}else{
					$(target).find(tabobj).find('a').find('img').attr('title',sortmessage+$(target).find(tabobj).find('a').find('img').attr('title')).attr('alt',sortmessage+$(target).find(tabobj).find('a').find('img').attr('alt'));
					$(target).find(tabobj).attr('class',$(target).find(tabobj).attr('class')+' '+'sortdesc');
					$(target).find(tabobj).find('a').focus();
					}
				}
			}  // post-submit callback 
				
				// other available options: 
				//target:    null        // target element(s) to be updated with server response 
				//url:       url         // override for form's 'action' attribute 
				//type:      type        // 'get' or 'post', override for form's 'method' attribute 
				//dataType:  null        // 'xml', 'script', or 'json' (expected server response type) 
				//clearForm: true        // clear all form fields after successful submit 
				//resetForm: true        // reset the form after successful submit 
				
				// $.ajax options can be used here too, for example: 
				//timeout:   3000 
			};
			
			// ajax form request
			var originalActionLink=$(formId).attr("action");
			$(formId).attr("action",url);
			$(formId).ajaxSubmit(options);
			$(formId).attr("action",originalActionLink);
		});
	}else{
		// load the page of url and update target element in ajax way
		$.ajax({
			url: url,
			cache: false,
			success: function(responseText){
				// force user to login page if session timeout
				if(!ajaxRequestSessionTimeout(responseText)){
					// clean up error message
					removeError();
					// in case the responseText is not XML like, which is jQuery required for analyzing
					wrappedResponseText = "<div id='responseTextWrapperDiv'>" + responseText + "</div>";
					prompts=$(target).find(".prompts:first");
					var content=$(prompts).html();
					$(target).html($(wrappedResponseText).find(target).html());
					report = $(target).find(".contentbox:first");
					$(prompts).html(content).prependTo(report);
					if("true"==ascending){
					$(target).find(tabobj).find('a').find('img').attr('title',sortmessage+$(target).find(tabobj).find('a').find('img').attr('title')).attr('alt',sortmessage+$(target).find(tabobj).find('a').find('img').attr('alt'));
					$(target).find(tabobj).attr('class',$(target).find(tabobj).attr('class')+' '+'sortasc');
					$(target).find(tabobj).find('a').focus();
					}else{
					$(target).find(tabobj).find('a').find('img').attr('title',sortmessage+$(target).find(tabobj).find('a').find('img').attr('title')).attr('alt',sortmessage+$(target).find(tabobj).find('a').find('img').attr('alt'));
					$(target).find(tabobj).attr('class',$(target).find(tabobj).attr('class')+' '+'sortdesc');
					$(target).find(tabobj).find('a').focus();
					}
				}
			}
		});	
	}
}

/*
 * If ajax request is session timeout then redirect user to login page with error message.
 * Return true if session timeout, otherwise false.
 */
function ajaxRequestSessionTimeout(responseText){
	if(responseText.indexOf('j_username') > 1){
		// judge herf layer and redirect
		if(window.location.href.indexOf('/hierarchy/') > 1){
			window.location = "../login.do?session_timeout=1";
		} else {
			window.location = "./login.do?session_timeout=1";
		}
		// session timeout
		return true;
	}
	
	// not session timeout
	return false;
}

/*
 * Bind input element's action with relative radio button in <report>.<prompts>.<group>.
 * If the element was selected, the relative radio button should be selected accordingly.
 */
function bindRadioButtonWithReportPromptsItem(reportPromptsItem, radioButtonName){
	// the dom hierarchy of 'this' object is: this < li < ul < div < form	
	// selector of radio button(s)
	radioSelector = "input[name='" + radioButtonName + "']";
	// unchecked all radio buttons
	$(radioSelector).attr('checked', false);
	// checked the relative one
	$(reportPromptsItem).parent().parent().find(radioSelector).attr('checked', true);
}

function reloadReport(url){
//	reportBodyDivId = $("div#maincontent div:last-child").attr("id");
	formName = $("div[id^='prompts'] form ").attr("id");
	reportId = document.forms[formName].reportId.value;
	reportBodyDivId = "div#report_body_" + reportId + "_tr1";
	ajaxLoadForForm(formName, reportBodyDivId);
}

function changeTitle()
{
	document.title = document.title + " - " + $("div#pageheading").text();
}

function insertPrompts(classId){
	$(".prompts").each(function(i){
	prompts = "div#" + $(this).attr("id");
	report = "div#" + $(this).next().attr("id") + " ." + classId + ":first";
	$(prompts).remove().insertBefore(report);
	});
}



function combineBatchPrompts(){
	$(".prompts").each(function(i){
		prompts = "div#" + $(this).attr("id");
		var movedNode = $(prompts + " div.tablelayout div.wrapper");
		
		if(movedNode.length==2){
		    var targetDivs = $(prompts + " div.tablelayout div.wrapper div.cell150");
			var anotherDivs = $("div#prompts_tr0 div.tablelayout div.wrapper div.cell150");
			
		  if(targetDivs.length==3&&anotherDivs.length==14){
		    
		    if(targetDivs[0].innerHTML==anotherDivs[0].innerHTML&&targetDivs[1].innerHTML==anotherDivs[1].innerHTML);
		     movedNode = $(movedNode[1]);
		  }
		 
		}
		movedNode.insertBefore("div#prompts_tr0 div.tablelayout div.wrapper:last");
		$(prompts).remove();
	});
}


function removePrompts(promptsId){
	$("div#"+promptsId).remove();
}

function getAnotherChart(){
	var form=document.getElementById('reportForm');  
	 getRadioPosition();
	 form.submit();
}

function getRadioPosition(){
	var form=document.getElementById('reportForm');  
	var form1=document.getElementById('reportForm1');  
	var chartArray=form1.elements['chartId'];
	var ci;
	for(var i=0;i<chartArray.length;i++){
		if(chartArray[i].checked){
			ci=chartArray[i].value;
			break;
		}
	}
	var chartId="chartId";
	if(form.action.indexOf(chartId)<0)
	form.action+='?chartId='+ci;
	
}
/** This method is replaced by isDisputeDisplay(xml)
function hideDisputeButton(){
	if(document.forms['reportForm'].statementCombineKey.type=='select-one'){
		if(!document.forms['reportForm'].statementCombineKey.options[0].selected){
			 $("div .hide").prev().hide();
		}}else{
			 $("div .hide").prev().show();
		}
}*/

function getFocus(inputType,inputName){
   $(function(){
       if("input"==inputType){
	    $("input[name='"+inputName+"']").focus();
		}
	  if("select"==inputType){
	   $("select[name='"+inputName+"']").focus();
		}
   })
}

function toggleMenu(id){	
	if($("#"+id).hasClass("displayBlock")){
		$("#"+id).removeClass("displayBlock");
		$("#"+id).addClass("displayNone");
		$("#tabs").removeClass("displayBlock");		
		$("#tabs").addClass("displayNone");
		document.getElementById('menuswitch').value = 'Show Menu';
	}
	else{
		  $("#"+id).removeClass("displayNone");
		  $("#"+id).addClass("displayBlock");
		  $("#tabs").removeClass("displayNone");
		  $("#tabs").addClass("displayBlock");		  
		  document.getElementById('menuswitch').value = 'Hide Menu';
	}
}

function setDivFocus(divName) {
		var messageobj=$(divName);
		if($(messageobj)[0]){
			$(messageobj).attr("tabindex","0"); 
			$(messageobj)[0].focus();
		}
}

function getStatementsForAccount(accountNumber,invokeMethod){
    var myurl="getStatementsByAccount.action";
    var mydata="account="+accountNumber;
    var statementKeyNode= $("#statementCombineKey");
    $.ajax({type:"POST", data:mydata, url:myurl,dataType:'xml',success:function(xml){
        if(statementKeyNode[0].nodeName=='INPUT'){
            if($(xml).find("statement").find("statementKey").length==1){
                $("#statementCombineKey").val($(xml).find("statement").find("statementKey").text());
                $("div",$("#statementCombineKey").parent()).text($(xml).find("statement").find("statementDate").text());
            }else{
                var statementKeyParent = $("#statementCombineKey").parent();
                if($("#statementCombineKey")[0].tagName == "INPUT"){
                    $("#statementCombineKey").prev().remove();
                    if(invokeMethod =="getPremiseAddressByAccount"){
                        $("#statementCombineKey").replaceWith("<select name='statementCombineKey' id='statementCombineKey' onchange='getPremiseAddressByAccount(document.getElementById(\"accountId\").value,document.getElementById(\"statementCombineKey\").value.split(\"|\")[1],document.getElementById(\"statementCombineKey\").value.split(\"|\")[0]);hideDisputeButton();'/>");
                    }else if(invokeMethod == "getServiceByAccountStatement"){
                        $("#statementCombineKey").replaceWith("<select name='statementCombineKey' id='statementCombineKey' onchange='getServiceByAccountStatement(document.getElementById(\"accountId\").value,document.getElementById(\"statementCombineKey\").value.split(\"|\")[1],document.getElementById(\"statementCombineKey\").value.split(\"|\")[0]);hideDisputeButton()'/>");
                    }else{
                        $("#statementCombineKey").replaceWith("<select name='statementCombineKey' id='statementCombineKey' onchange='getStatementNumberByAccountNumber(document.getElementById(\"accountId\").value);' />");

                    }
                }else{
                    statementKeyParent.empty();
                }
                $(xml).find("statement").each(function(){
                    var statementKey = $(this).find("statementKey").text();
                    var statementDate = $(this).find("statementDate").text();
                    $("#statementCombineKey").append("<option value="+statementKey+">"+statementDate+"</option>");
                });
            }
        }else{
            if($(xml).find("statement").size()<=1){
                $("#statementCombineKey").replaceWith("<div class='labelbold'>"+$(xml).find("statement").find("statementDate").text()+"</div><input type='hidden' value='"+$(xml).find("statement").find("statementKey").text()+"' id='statementCombineKey' name='statementCombineKey'>");
            }else{
                if(invokeMethod =="getPremiseAddressByAccount"){
                    $("#statementCombineKey").replaceWith("<select name='statementCombineKey' id='statementCombineKey' onchange='getPremiseAddressByAccount(document.getElementById(\"accountId\").value,document.getElementById(\"statementCombineKey\").value.split(\"|\")[1],document.getElementById(\"statementCombineKey\").value.split(\"|\")[0]);hideDisputeButton();'/>");
                }else if(invokeMethod == "getServiceByAccountStatement"){
                    $("#statementCombineKey").replaceWith("<select name='statementCombineKey' id='statementCombineKey' onchange='getServiceByAccountStatement(document.getElementById(\"accountId\").value,document.getElementById(\"statementCombineKey\").value.split(\"|\")[1],document.getElementById(\"statementCombineKey\").value.split(\"|\")[0]);hideDisputeButton()'/>");
                }else{
                    $("#statementCombineKey").replaceWith("<select name='statementCombineKey' id='statementCombineKey' onchange='getStatementNumberByAccountNumber(document.getElementById(\"accountId\").value);' />");
                }
                $(xml).find("statement").each(function(){
                    var statementKey = $(this).find("statementKey").text();
                    var statementDate = $(this).find("statementDate").text();
                    $("#statementCombineKey").append("<option value="+statementKey+">"+statementDate+"</option>");
                });
            }
        }
        if(invokeMethod =="getPremiseAddressByAccount"){
            var statementKey = $(xml).find("statement").find("statementKey")[0];
            var keys = statementKey.firstChild.data.split("|");
            getPremiseAddressByAccount(accountNumber,keys[1],keys[0]);
        }else if(invokeMethod == "getServiceByAccountStatement"){
            var statementKey = $(xml).find("statement").find("statementKey")[0];
            var keys = statementKey.firstChild.data.split("|");
            getServiceByAccountStatement(accountNumber,keys[1],keys[0]);
        }
    getStatementNumberByStatementDate(xml);
    }
    });
    $("div .hide").prev().show();
  
}

function getStatementNumberByStatementDate(statementxml){
	var statementCombineKey=document.getElementById('statementCombineKey').value;
        $(statementxml).find("statement").each(function(){
            var statementKey = $(this).find("statementKey").text();
            if(statementKey==statementCombineKey){
		      $("div",$("#statementNumber").parent()).text($(this).find("statementNumber").text());
			  $("#statementNumber").val($(this).find("statementNumber").text());
			  return false;
            }
        });
}

function getPeriodForStatement(obj){
var outerParent = $(obj).parent().parent();
var buttons = $('input[type="button"]',outerParent);


try    {   
       for(var i=0;i<buttons.length;i++){
            buttons[i].disabled="disabled";
        }
		if($("#reportPeriodStart")[0].nodeName=='SELECT'){
    var val = obj.value;
    var accountNumber = $("#accountId").val();
    var myurl="getStatementsByAccount.action";
    var mydata="accountNumber="+accountNumber;
	$.ajax({type:"POST", data:mydata, url:myurl,dataType:'xml',success:function(xml){
   

	$("#reportPeriodStart").empty();
	
    $(xml).find("statement").each(function(){
    
    


     var periodKey = $(this).find("periodKey").text();
     $("#reportPeriodStart").append("<option value="+periodKey+">"+periodKey+"</option>");
    });
	
	
	var options = $("#statementCombineKey>option");
	var index = 0;
	for(var i=0;i<options.length;i++){
	       if(options[i].value==val){
		     index=i;
			 break;
		   }
		      
	}
	
	
	$("#reportPeriodStart option:nth-child("+(index+1)+")")[0].selected=true;
  
	
	}
	
	});
	
}
     
   }   
   catch(e)    {   
       
   }   
   finally    {   
       for(var i=0;i<buttons.length;i++){
    buttons[i].disabled="";
     }
   }   



	
	
	
	
	
}

function setFocusOnForm(){
	$(":input:visible:enabled").each(function() {
		if ((($(this).attr('type') == 'text')||($(this).attr('type') == 'password')||($(this).attr('type') == 'radio')||($(this).attr('type') == 'checkbox')||($(this).attr('type') == 'file')) && (!$(this).attr('readonly')) && ($(this).is('input'))){
		$(this).focus();
	    return false;
		}
		if ($(this).is('textarea')){
		$(this).focus();
		return false;
		}
		if ($(this).is('select')&&$(this).attr('name')!='format'){
		$(this).focus();
		return false;
		}
	});
}

function setAriaDescribedByAttr(){
	var inputFieldElementCntr = 0;
	$(":input:visible:enabled").each(function() {

		if (inputFieldElementCntr == 0){
			if ((($(this).attr('type') == 'text')||($(this).attr('type') == 'password')||($(this).attr('type') == 'radio')||($(this).attr('type') == 'checkbox')||($(this).attr('type') == 'file')) && (!$(this).attr('readonly')) && ($(this).is('input'))){
			$(this).attr("aria-describedby","errormessage "+ $(this).attr('id') + "ErrorMessage warnmessage infomessagefocus");
			$(this).focus();
			inputFieldElementCntr++;
			}
			if ($(this).is('textarea')){
			$(this).attr("aria-describedby","errormessage "+$(this).attr('id') + "ErrorMessage warnmessage infomessagefocus");
			$(this).focus();
			inputFieldElementCntr++;
			}
			if ($(this).is('select')&&$(this).attr('name')!='format'){
			$(this).attr("aria-describedby","errormessage "+$(this).attr('id')+"ErrorMessage warnmessage infomessagefocus");
			$(this).focus();
			inputFieldElementCntr++;
			}
		} else {
			if ((($(this).attr('type') == 'text')||($(this).attr('type') == 'password')||($(this).attr('type') == 'radio')||($(this).attr('type') == 'checkbox')||($(this).attr('type') == 'file')) && (!$(this).attr('readonly')) && ($(this).is('input'))){
			$(this).attr("aria-describedby",$(this).attr('id')+"ErrorMessage");
			inputFieldElementCntr++;
			}
			if ($(this).is('textarea')){
			$(this).attr("aria-describedby",$(this).attr('id')+"ErrorMessage");
			inputFieldElementCntr++;
			}
			if ($(this).is('select')&&$(this).attr('name')!='format'){
			$(this).attr("aria-describedby",$(this).attr('id')+"ErrorMessage");
			inputFieldElementCntr++;
			}
		}
		
	});
}

function displayErrorMsg() {
	/* Remove duplicate errormessage */
	$('.errormessage').last().remove();
	
	/* Place errormessage before start of first content box */
	$('.contentbox').first().before($('.errormessage'));

	/* remove displayNone style class for div id maincontent  */
	$('#maincontent').removeClass("displayNone");
}


function makeCalendarImageTabbed(textID){
	var inputText = document.getElementById(textID);
	inputText.setAttribute("onfocus","focusCalendarInputText('"+textID+"');");
}
function focusCalendarInputText(inputTextID){
	var inputText=document.getElementById(inputTextID);
	inputText.nextSibling.setAttribute('tabindex','0');
	inputText.nextSibling.setAttribute('id',inputTextID+'CalendarImage');
	showDatepickerByEnter(inputTextID);
	if(!document.getElementById(inputTextID+"hiddenAnchor")){
		var hiddenAnchor = document.createElement("a");
		hiddenAnchor.setAttribute("href","#");
		hiddenAnchor.setAttribute("onclick","return false;");
		hiddenAnchor.setAttribute("id",inputTextID+"hiddenAnchor");
		hiddenAnchor.innerHTML="Not Used";
		hiddenAnchor.setAttribute("class","hiddenAnchor");
		hiddenAnchor.setAttribute("onfocus","focusCalendarImage('"+inputTextID+"',this);");
		inputText.parentNode.appendChild(hiddenAnchor);							
	}
}
function focusCalendarImage(inputTextID,removedNode){
	var inputText = document.getElementById(inputTextID);
	inputText.nextSibling.focus();
	inputText.parentNode.removeChild(removedNode);
}
function showDatepickerByEnter(inputTextID) {
	$('#'+inputTextID+'CalendarImage').keypress(function(event){ 
		var keycode = (event.keyCode ? event.keyCode : event.which);
		if(keycode == '13'){
			$("#"+inputTextID).datepicker("show");
			$("#ui-datepicker-div").attr("tabindex","0");
			$("#ui-datepicker-div").focus();
			return false;
		} 	
	});					
}

function previousBalanceClick(){
	  var accountId = $("#accountId").val();
	  $("#statementCombineKey option:selected + option")[0].selected = true;
	  var statementCombineKey = $("#statementCombineKey").val();
	  var url = "stmtrpt.action?reportId=StatementSummary&accountNumber="+accountId+"&statementCombineKey="+statementCombineKey;
	  window.location = url;
	  
	}

function clickTreeNode(url){
	var reportPeriodStart = url.split('reportPeriodStart=')[1];
	var myurl="statement/"+url.replace('stdrill.action','getStatementsFromTreeNode.action');
	var flag = true;
			 $.ajax({type:"POST",  url:myurl,dataType:'xml',success:function(xml){
				 $(xml).find("statement").each(function(){
        var statementCombineKey = $(this).find("statementKey").text();
        var periodKey = statementCombineKey.split("|")[1];
				if((periodKey == reportPeriodStart)&&flag){
					flag=false;
				    window.location = url +"&statementCombineKey="+statementCombineKey;
				}
    });
			 
 }
 });
			
}


function makeDivTabbed(divID,priorTabID){

	var inputText = document.getElementById(priorTabID);
	inputText.setAttribute("onfocus","focusPriorTab('"+divID+"','"+priorTabID+"');");
}
function focusPriorTab(divID,priorTabID){
	var tabbedDiv=document.getElementById(divID);
	if(tabbedDiv.nodeName=="DIV"){
		tabbedDiv.setAttribute('tabindex','0');
	}	
	if(!document.getElementById(divID+"hiddenAnchor")){
		var hiddenAnchor = document.createElement("a");
		hiddenAnchor.setAttribute("href","#");
		hiddenAnchor.setAttribute("onclick","return false;");
		hiddenAnchor.setAttribute("id",divID+"hiddenAnchor");
		hiddenAnchor.innerHTML="Not Used";
		hiddenAnchor.setAttribute("class","hiddenAnchor");
		hiddenAnchor.setAttribute("onfocus","focusTabbedDiv('"+divID+"',this,'"+priorTabID+"');");
		document.getElementById(priorTabID).parentNode.appendChild(hiddenAnchor);
	}
}
function focusTabbedDiv(divID,removedNode,priorTabID){
	document.getElementById(divID).focus();
	document.getElementById(priorTabID).parentNode.removeChild(removedNode);
}

function enAbleHotKey(){
var count=1;
$(document).bind('keydown','Ctrl+return', function(){
 var searchButton=$("div[id^='prompts_'] :submit,div[id^='prompts_'] :button");
 if($(searchButton)[0]){
	 $(searchButton)[0].click();
}});

$(document).bind('keydown','Ctrl+Shift+x', function(){
if(count==1){
window.location.href=$("a#logoutlink").attr("href");
count++;
}
});
}

function processLogo(app){
	var logo = $('<img/>').addClass('hiddenReadableElement').attr('src',app+'/_assets/images/blankSpace.gif').attr('alt','Corporate Logo'); 
	$(function(){
	var logoobj=$("div[id='logo']");
	if($(logoobj)[0]){
	$(logoobj).after(logo);
	}
	});
	}

function processActiveTab(){
	$(function(){
	var tab=$("ul[id='tabs']").children(".active");
	if($(tab)[0]){
	$(tab).children().removeAttr("href");
	}
	var subtab=$("ul[id='subtabs']").children(".active")
	if($(subtab)[0]){
	$(subtab).children().removeAttr("href"); 
	}
	var pagetab=$("div[class='pagetabs']").children().children(".active")
	if($(pagetab)[0]){
	$(pagetab).children().removeAttr("href"); 
	}
	});
	}

function processErrAndMesFocus(app){
	var erricon = $('<img/>').attr('src',app+'/_assets/skin/error.gif').attr('alt',''); 
	$(function(){
	
	var infoobj=$("div[class='infomessagefocus']");
	if($(infoobj)[0]){
	    $(infoobj).attr("tabindex","0");
	    $(infoobj).attr("id","infomessagefocus");
	    $(infoobj)[0].focus();
	}
	var warnobj=$("div[class='warnmessage']");
	if($(warnobj)[0]){
	$(warnobj).attr("tabindex","0");
	$(warnobj).attr("id","warnmessage");
	$(warnobj)[0].focus();
	}	   
	var errobj=$("div[class='errormessage']");
	if($(errobj)[0]){
	$(errobj).attr("tabindex","0");
	$(errobj).attr("id","errormessage");
	$(errobj)[0].focus();
	$(errobj).find("div[class='erroricon']").append(erricon);
	}
	var subtitleobj=$("div[class='subtitle']");
	if(!($(infoobj)[0] || $(warnobj)[0] || $(errobj)[0])){
	    if($(subtitleobj)[0]){
	        $(subtitleobj).attr("tabindex","0");
	        $(subtitleobj)[0].focus();
     }	
	}else{
	    if($(subtitleobj)[0]){
	        $(subtitleobj).attr("tabindex","0");
     }	
	}
	
	setFocusOnForm();
	
	//To fix Bug 14053689
	var errmessage=$("div[class='errormessage']>ul[class='errorMessage']");
	if(errmessage.size()>1) {
	    errmessage.each(function(index,element) {
	      var test= index;
	       if(index !=0) {
	         var content=$(element).html();
	         $(content).appendTo($("div[class='errormessage']>ul[class='errorMessage']:first"));
	         $(element).remove();
	       }
	    });
	}
	
	var sucobj=$("div[class='successmessage']");
	if($(sucobj)[0]){
	    $(sucobj).attr("tabindex","0");
	    $(sucobj)[0].focus();
	}
    var pageheadingobj=$("div[id='pageheading']");
    if($(pageheadingobj)[0]){
        $(pageheadingobj).attr("tabindex","0");
    }
	});
	}

function processMarkupForUL(messageHead,messageEnd){
	$(function(){
	var ulObjs = $("ul:not(.errorMessage, .actionMessage)");
	for(var i=0;i<$(ulObjs).length;i++){
	var curList=ulObjs[i];
	var curListChild=$(curList).children("li");
	var messageStr="";
	var endStr="";
	for(var j=0;j<$(curListChild).length;j++){
	    if(j==1){
	    messageStr+=",";
	    }
	    if(j>1){
	    endStr=messageEnd;
	    break;
	    }
	    messageStr+=$.trim($(curListChild[j]).text());
	}
	$(curList).before("<div class='hiddenReadableElement'><h4>"+messageHead+" "+messageStr+" "+endStr+"<\/h4><\/div>");
	}
	});
	}

function processButtonLabel(buttonfor,resetlabel,resetmessage){
	$(":submit,:button,:reset").each(function(){
	if($(this).attr("title")){
	$(this).attr("aria-label",$(this).attr("title")+" "+buttonfor+" "+$.trim($("div#pageheading").text()));
	}else{
	$(this).attr("aria-label",$(this).attr("value")+" "+buttonfor+" "+$.trim($("div#pageheading").text()));
	}
	if(resetlabel==$(this).attr("value")){
	$(this).attr("aria-label",$(this).attr("aria-label")+":"+resetmessage);
	}
	});
	}

function processSessionTimeout(period,timeoutmessage,app,logout,timeout){
			$(document).ready(function() {
	    $.sessionTimeout({
	        warnAfter: period-60000,
	        redirAfter: period,
			keepAliveUrl:app+"/includes/blank.jsp",
			logoutUrl:app+logout,
			redirUrl:app+timeout,
			message:timeoutmessage
			
	    });
	});
	}

function processUnuniformTable(ununiformmessage) {

     $('.contentbox .rpt').each(function() {
	     var colspanList = $(this).find('td[colspan]');
		 if($(colspanList)[0]) {

		    if($(colspanList).attr("colspan") > 1) {
		         var summary = " " + $(this).attr('summary');
		         $(this).attr('summary', ununiformmessage + summary);
		    }
		 }
	 });
}

function clickPrintSummary(prefix){
	var accountId = document.getElementById('accountId').value;
	var statementCombineKey = document.getElementById('statementCombineKey');
	if(statementCombineKey!=null) {
		window.location.href=prefix+'?reportId=statementGST&type=pdf&templateId=PDF_TEMPLATE&clearCachedSessionRpt=false&accountId='+accountId+'&statementCombineKey='+statementCombineKey.value;
	} else {
		window.location.href=prefix+'?reportId=statementGST&type=pdf&templateId=PDF_TEMPLATE&clearCachedSessionRpt=false&accountId='+accountId;
	}
}

function sortSelect(selectID) {
	var selectObject = document.getElementById(selectID);
	if(selectObject&&selectObject.options){
        var optionArray = new Array();
        for (var i=0;i<selectObject.options.length;i++) {
            optionArray[i] = new Array();
            optionArray[i][0] = selectObject.options[i].text;
            optionArray[i][1] = selectObject.options[i].value;
			if(selectObject.options[i].selected)
				 optionArray[i][2] = "selected"
			else
				 optionArray[i][2] = "";
        }
        optionArray.sort();
        while (selectObject.options.length > 0) {
            selectObject.innerHTML="";
        }
        for (var i=0;i<optionArray.length;i++) {
            var op = new Option(optionArray[i][0], optionArray[i][1]);
			if(optionArray[i][2] == "selected")
				op.setAttribute("selected","selected");
            selectObject.options[i] = op;
        }		
	}
    return;
}
function addAutocompleteAttribute(){
	var inputText = "input[type='text']";
	// unchecked all radio buttons
	$(inputText).attr('autocomplete', 'off');
}

//ADA Bug 14460816
function dealWithButton() {
    $(document).ready(function() {
        $(".markButton").each(function(){
			var self = $(this),
				findForm = self.closest("form");

			self.attr("disabled", true);

			findForm.find("select, radio, input").each(function() {
				$(this).bind("change", function(evt) {
					self.removeAttr('disabled');
				});
				$(this).bind("keyup", function(){
					$(this).blur();
					$(this).focus();
	        	});
			});
			findForm.find("input[type=text]").each(function() {
				$(this).bind("keyup", function(evt) {
					if(!isEventequalsTAB(evt)) {
						self.removeAttr('disabled');
					}
				});
			});
        });
    });
}

//Check event's position is in target
function checkCollision(e, targetId) {
	var eventX = e.clientX,
	    eventY = e.clientY,
	    left = $(targetId).offset().left, 
	    top =  $(targetId).offset().top,
	    width = $(targetId).width(), 
	    height = $(targetId).height();

	if(eventX < left || eventY < top || eventX > (left + width) || eventY > (top + height))
		return true;
	else
		return false;
}

//fix ADA BUG 14664200 
function processHeader(pageTabHeader){
	$("div.subtitle").each(function(){
		 $(this).html('<h2 id="datamessage">'+$.trim($(this).html())+'</h2>');
		 });
	$("div.pagetabs ul").each(function(){
		 $(this).before('<h4 class="hiddenReadableElement">'+pageTabHeader+'</h4>');
		 });
}
function resetBootStrapUser(formID,action){
	var form = document.getElementById(formID);
	form.action=action;
	form.submit();
}

function singleSubmit(formId){
	$(document).ready(function(){
		$('#'+formId).submit();
		$('#'+formId+' :input[type="submit"]').attr('disabled', 'disabled');
	});
}
//End of script

// GridTree Start --------------------------------------------------------------------

function GridTree(treeId){
    this.sap = {ui:{keycodes:{
        SPACE: 32,
        ENTER: 13,
        ARROW_LEFT : 37,
        ARROW_UP : 38,
        ARROW_RIGHT : 39,
        ARROW_DOWN : 40,
        TAB: 9
    }}};

    this.grids = [];

    this.initGrid(treeId);
}

GridTree.prototype.getGrid = function(id) {
    if (!this.grids[id]) {
        var grid = {};

        grid.focusedRow = 1;
        grid.focusedCol = 0;
        grid.focusedCell = null;
        grid.selectedRow = -1;
        grid.table = $("#"+id)[0];

        this.grids[id] = grid;
    }
    return this.grids[id];
}

GridTree.prototype.initGrid = function(id){
    var grid = this.getGrid(id);

    var thisObj = this;

    if (grid) {
        // bind a click handler
        grid.table.onclick = function(event) {
            return thisObj.handleClick(event, id);
        };

        // bind a keydown handler
        grid.table.onkeydown = function(event) {
            return thisObj.handleKeyDown(event, id);
        };

        if (!grid.focusedCell) {
            grid.focusedCell = { row: 1, col: 0 };
            this.focusCell(grid.focusedCell, grid);
        } else {
            this.blurCell(grid.focusedCell, grid);
        }
    }
}

GridTree.prototype.handleClick = function(e, id) {

    var grid = this.getGrid(id);

    if (grid) {
        if (!e) e = window.event; // IE
        var clickedEl = e.target ? e.target : e.srcElement;

        switch (clickedEl.nodeName) {
            case "TD":{
                this.blurCell(grid.focusedCell, grid);
                grid.focusedRow = clickedEl.parentNode.rowIndex;
                var row = grid.table.rows[grid.focusedRow];
                for (var i = 0; i < row.cells.length; i++) {
                    if (row.cells[i] == clickedEl) {
                        grid.focusedCol = i;
                        break;
                    }
                }
                // update grid
                grid.focusedCell = { row: grid.focusedRow, col: grid.focusedCol };

                // focus the new cell
                this.focusCell(grid.focusedCell, grid)
                break;
            }
            case "SPAN":{
                this.blurCell(grid.focusedCell, grid);
                grid.focusedRow = clickedEl.parentNode.parentNode.rowIndex;
                var row = grid.table.rows[grid.focusedRow];
                for (var i = 0; i < row.cells.length; i++) {
                    if (row.cells[i] == clickedEl.parentNode) {
                        grid.focusedCol = i;
                        break;
                    }
                }

                // update grid
                grid.focusedCell = { row: grid.focusedRow, col: grid.focusedCol };

                // focus the new cell
                this.focusCell(grid.focusedCell, grid)
                break;
            }
            default:
                break;
        }
    }
    return true;
}

GridTree.prototype.handleKeyDown = function(e, id) {
    var grid = this.getGrid(id);

    if (grid) {
        if (!e) e = window.event; // IE

        keyCode = e.keyCode;
        evtTarget = e.target ? e.target : e.srcElement;

        if ((e.altKey || e.ctrlKey)
            || (e.shiftKey && e.keyCode != this.sap.ui.keycodes.TAB)) {
            // do nothing
            return true;
        }

        switch (keyCode){
            case this.sap.ui.keycodes.ARROW_LEFT:{
                this.focusPreviousCell(grid);
                break;
            }
            case this.sap.ui.keycodes.ARROW_RIGHT:{
                this.focusNextCell(grid);
                break;
            }
            case this.sap.ui.keycodes.ARROW_UP:{
                this.focusPreviousRow(grid);
                break;
            }
            case this.sap.ui.keycodes.ARROW_DOWN:{
                this.focusNextRow(grid);
                break;
            }
            case this.sap.ui.keycodes.ENTER:{
                var aTarget = $(evtTarget).children('a')[0]
                if(aTarget){
                    aTarget.click();
                }
                break;
            }
            case this.sap.ui.keycodes.TAB:{
                this.blurCell(grid.focusedCell, grid);

                // restore entry point on table exit for next time focus is set back to grid
                var td = grid.table.rows[grid.focusedCell.row].cells[grid.focusedCell.col];

                if (td) {
                    td.tabIndex = "0";
                }
                break;
            }
        }
    }
    return true;
}


GridTree.prototype.blurCell = function(cell,grid) {
    var td = grid.table.rows[cell.row].cells[cell.col];
    if (td) {
        td.tabIndex = "-1";
    }
}


GridTree.prototype.focusCell = function(cell, grid) {
    var td = grid.table.rows[cell.row].cells[cell.col];
    if (td) {
        td.tabIndex = "0";
        td.focus();
    }
}


GridTree.prototype.focusNextRow = function(grid) {
    row = grid.table.rows[grid.focusedRow];

    try {
        for (i=0; i<=row.cells.length-1; i++) {
            row.cells[i].tabIndex = "-1";
        }    // remove tab index from all actual row members (cells)

        if (grid.table.rows[row.rowIndex + 1]){ // find next row
            nextRow = grid.table.rows[row.rowIndex + 1];
        }else { // must be at the end
            nextRow = grid.table.rows[grid.table.rows.length - 1];
        }

        //skip non-visible rows
        while (nextRow && nextRow.style.display == "none") {
            nextRow = grid.table.rows[nextRow.rowIndex + 1];
        }

        if (nextRow) {
            if (nextRow.cells[grid.focusedCol]) {
                nextRow.cells[grid.focusedCol].tabIndex = "0";
                nextRow.cells[grid.focusedCol].focus();
            }else {
                nextRow.cells[0].tabIndex = "0";
                nextRow.cells[0].focus();
            }

            grid.focusedRow = nextRow.rowIndex;
            grid.focusedCell = { row: grid.focusedRow, col: grid.focusedCol };
        }
    }catch (Error) { }
}


GridTree.prototype.focusPreviousRow = function(grid) {
    row = grid.table.rows[grid.focusedRow];

    try {
        for (i=0; i<=row.cells.length-1; i++) {
            row.cells[i].tabIndex = "-1";
        }  // remove tab index from all actual row members (cells)

        if (grid.table.rows[row.rowIndex - 1]){ // find previous row
            previousRow = grid.table.rows[row.rowIndex - 1];
        }else {// must be at the begin
            previousRow = grid.table.rows[0];
        }

        //skip non-visible rows
        while (previousRow && previousRow.style.display == "none") {
            previousRow = grid.table.rows[previousRow.rowIndex - 1];
        }

        if (previousRow) {
            if (previousRow.cells[grid.focusedCol]) {
                previousRow.cells[grid.focusedCol].tabIndex = "0";
                previousRow.cells[grid.focusedCol].focus();
            }else {
                previousRow.cells[0].tabIndex = "0";
                previousRow.cells[0].focus();
            }

            grid.focusedRow = previousRow.rowIndex;
            grid.focusedCell = { row: grid.focusedRow, col: grid.focusedCol };
        }
    } catch (Error) { }
}


GridTree.prototype.focusNextCell = function(grid) {
    var row = grid.table.rows[grid.focusedRow];

    try {
        if (row.cells.length>1) {
            if (grid.focusedCol<row.cells.length-1) {
                var cell=row.cells[grid.focusedCol];
                cell.tabIndex="-1";
                grid.focusedCol++;
                var cell=row.cells[grid.focusedCol];
                cell.tabIndex="0";
                cell.focus();
            }
        }
    } catch (Error) { }
}


GridTree.prototype.focusPreviousCell = function(grid) {
    var row = grid.table.rows[grid.focusedRow];

    try {
        if (row.cells.length>1) {
            if (grid.focusedCol>0) {
                var cell=row.cells[grid.focusedCol];
                cell.tabIndex="-1";
                grid.focusedCol--;
                var cell=row.cells[grid.focusedCol];
                cell.tabIndex="0";
                cell.focus();
            }
        }
    }catch (Error) { }
}

function dealPayUpdate(flag) {
	if(flag){
		$(".update").attr("disabled", true);
	}else{
		$(".update").removeAttr('disabled');
	}
}

// GridTree End --------------------------------------------------------------------